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.
|
[
"package api",
"type Shortcut struct {\n\tID int `json:\"id\"`",
"\t// Standard fields\n\tRowStatus RowStatus `json:\"rowStatus\"`\n\tCreatorID int `json:\"creatorId\"`\n\tCreatedTs int64 `json:\"createdTs\"`\n\tUpdatedTs int64 `json:\"updatedTs\"`",
"\t// Domain specific fields\n\tTitle string `json:\"title\"`\n\tPayload string `json:\"payload\"`\n}",
"type ShortcutCreate struct {\n\t// Standard fields",
"\tCreatorID int",
"\n\t// Domain specific fields\n\tTitle string `json:\"title\"`\n\tPayload string `json:\"payload\"`\n}",
"type ShortcutPatch struct {\n\tID int `json:\"-\"`",
"\t// Standard fields\n\tUpdatedTs *int64\n\tRowStatus *RowStatus `json:\"rowStatus\"`",
"\t// Domain specific fields\n\tTitle *string `json:\"title\"`\n\tPayload *string `json:\"payload\"`\n}",
"type ShortcutFind struct {\n\tID *int",
"\t// Standard fields\n\tCreatorID *int",
"\t// Domain specific fields\n\tTitle *string `json:\"title\"`\n}",
"type ShortcutDelete struct {\n\tID *int",
"\t// Standard fields\n\tCreatorID *int\n}"
] |
[
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package api",
"type Shortcut struct {\n\tID int `json:\"id\"`",
"\t// Standard fields\n\tRowStatus RowStatus `json:\"rowStatus\"`\n\tCreatorID int `json:\"creatorId\"`\n\tCreatedTs int64 `json:\"createdTs\"`\n\tUpdatedTs int64 `json:\"updatedTs\"`",
"\t// Domain specific fields\n\tTitle string `json:\"title\"`\n\tPayload string `json:\"payload\"`\n}",
"type ShortcutCreate struct {\n\t// Standard fields",
"\tCreatorID int `json:\"-\"`",
"\n\t// Domain specific fields\n\tTitle string `json:\"title\"`\n\tPayload string `json:\"payload\"`\n}",
"type ShortcutPatch struct {\n\tID int `json:\"-\"`",
"\t// Standard fields\n\tUpdatedTs *int64\n\tRowStatus *RowStatus `json:\"rowStatus\"`",
"\t// Domain specific fields\n\tTitle *string `json:\"title\"`\n\tPayload *string `json:\"payload\"`\n}",
"type ShortcutFind struct {\n\tID *int",
"\t// Standard fields\n\tCreatorID *int",
"\t// Domain specific fields\n\tTitle *string `json:\"title\"`\n}",
"type ShortcutDelete struct {\n\tID *int",
"\t// Standard fields\n\tCreatorID *int\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package api",
"type Tag struct {\n\tName string\n\tCreatorID int\n}",
"type TagUpsert struct {\n\tName string",
"\tCreatorID int",
"}",
"type TagFind struct {\n\tCreatorID int\n}",
"type TagDelete struct {\n\tName string\n\tCreatorID int\n}"
] |
[
1,
1,
1,
0,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package api",
"type Tag struct {\n\tName string\n\tCreatorID int\n}",
"type TagUpsert struct {\n\tName string",
"\tCreatorID int `json:\"-\"`",
"}",
"type TagFind struct {\n\tCreatorID int\n}",
"type TagDelete struct {\n\tName string\n\tCreatorID int\n}"
] |
[
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package api",
"import (\n\t\"encoding/json\"\n\t\"fmt\"",
"\t\"golang.org/x/exp/slices\"\n)",
"type UserSettingKey string",
"const (\n\t// UserSettingLocaleKey is the key type for user locale.\n\tUserSettingLocaleKey UserSettingKey = \"locale\"\n\t// UserSettingAppearanceKey is the key type for user appearance.\n\tUserSettingAppearanceKey UserSettingKey = \"appearance\"\n\t// UserSettingMemoVisibilityKey is the key type for user preference memo default visibility.\n\tUserSettingMemoVisibilityKey UserSettingKey = \"memoVisibility\"\n\t// UserSettingMemoDisplayTsOptionKey is the key type for memo display ts option.\n\tUserSettingMemoDisplayTsOptionKey UserSettingKey = \"memoDisplayTsOption\"\n)",
"// String returns the string format of UserSettingKey type.\nfunc (key UserSettingKey) String() string {\n\tswitch key {\n\tcase UserSettingLocaleKey:\n\t\treturn \"locale\"\n\tcase UserSettingAppearanceKey:\n\t\treturn \"appearance\"\n\tcase UserSettingMemoVisibilityKey:\n\t\treturn \"memoVisibility\"\n\tcase UserSettingMemoDisplayTsOptionKey:\n\t\treturn \"memoDisplayTsOption\"\n\t}\n\treturn \"\"\n}",
"var (\n\tUserSettingLocaleValue = []string{\"en\", \"zh\", \"vi\", \"fr\", \"nl\", \"sv\", \"de\", \"es\", \"uk\"}\n\tUserSettingAppearanceValue = []string{\"system\", \"light\", \"dark\"}\n\tUserSettingMemoVisibilityValue = []Visibility{Private, Protected, Public}\n\tUserSettingMemoDisplayTsOptionKeyValue = []string{\"created_ts\", \"updated_ts\"}\n)",
"type UserSetting struct {\n\tUserID int\n\tKey UserSettingKey `json:\"key\"`\n\t// Value is a JSON string with basic value\n\tValue string `json:\"value\"`\n}",
"type UserSettingUpsert struct {",
"\tUserID int",
"\tKey UserSettingKey `json:\"key\"`\n\tValue string `json:\"value\"`\n}",
"func (upsert UserSettingUpsert) Validate() error {\n\tif upsert.Key == UserSettingLocaleKey {\n\t\tlocaleValue := \"en\"\n\t\terr := json.Unmarshal([]byte(upsert.Value), &localeValue)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting locale value\")\n\t\t}\n\t\tif !slices.Contains(UserSettingLocaleValue, localeValue) {\n\t\t\treturn fmt.Errorf(\"invalid user setting locale value\")\n\t\t}\n\t} else if upsert.Key == UserSettingAppearanceKey {\n\t\tappearanceValue := \"system\"\n\t\terr := json.Unmarshal([]byte(upsert.Value), &appearanceValue)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting appearance value\")\n\t\t}\n\t\tif !slices.Contains(UserSettingAppearanceValue, appearanceValue) {\n\t\t\treturn fmt.Errorf(\"invalid user setting appearance value\")\n\t\t}\n\t} else if upsert.Key == UserSettingMemoVisibilityKey {\n\t\tmemoVisibilityValue := Private\n\t\terr := json.Unmarshal([]byte(upsert.Value), &memoVisibilityValue)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting memo visibility value\")\n\t\t}\n\t\tif !slices.Contains(UserSettingMemoVisibilityValue, memoVisibilityValue) {\n\t\t\treturn fmt.Errorf(\"invalid user setting memo visibility value\")\n\t\t}\n\t} else if upsert.Key == UserSettingMemoDisplayTsOptionKey {\n\t\tmemoDisplayTsOption := \"created_ts\"\n\t\terr := json.Unmarshal([]byte(upsert.Value), &memoDisplayTsOption)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting memo display ts option\")\n\t\t}\n\t\tif !slices.Contains(UserSettingMemoDisplayTsOptionKeyValue, memoDisplayTsOption) {\n\t\t\treturn fmt.Errorf(\"invalid user setting memo display ts option value\")\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"invalid user setting key\")\n\t}",
"\treturn nil\n}",
"type UserSettingFind struct {\n\tUserID int",
"\tKey *UserSettingKey `json:\"key\"`\n}",
"type UserSettingDelete struct {\n\tUserID int\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package api",
"import (\n\t\"encoding/json\"\n\t\"fmt\"",
"\t\"golang.org/x/exp/slices\"\n)",
"type UserSettingKey string",
"const (\n\t// UserSettingLocaleKey is the key type for user locale.\n\tUserSettingLocaleKey UserSettingKey = \"locale\"\n\t// UserSettingAppearanceKey is the key type for user appearance.\n\tUserSettingAppearanceKey UserSettingKey = \"appearance\"\n\t// UserSettingMemoVisibilityKey is the key type for user preference memo default visibility.\n\tUserSettingMemoVisibilityKey UserSettingKey = \"memoVisibility\"\n\t// UserSettingMemoDisplayTsOptionKey is the key type for memo display ts option.\n\tUserSettingMemoDisplayTsOptionKey UserSettingKey = \"memoDisplayTsOption\"\n)",
"// String returns the string format of UserSettingKey type.\nfunc (key UserSettingKey) String() string {\n\tswitch key {\n\tcase UserSettingLocaleKey:\n\t\treturn \"locale\"\n\tcase UserSettingAppearanceKey:\n\t\treturn \"appearance\"\n\tcase UserSettingMemoVisibilityKey:\n\t\treturn \"memoVisibility\"\n\tcase UserSettingMemoDisplayTsOptionKey:\n\t\treturn \"memoDisplayTsOption\"\n\t}\n\treturn \"\"\n}",
"var (\n\tUserSettingLocaleValue = []string{\"en\", \"zh\", \"vi\", \"fr\", \"nl\", \"sv\", \"de\", \"es\", \"uk\"}\n\tUserSettingAppearanceValue = []string{\"system\", \"light\", \"dark\"}\n\tUserSettingMemoVisibilityValue = []Visibility{Private, Protected, Public}\n\tUserSettingMemoDisplayTsOptionKeyValue = []string{\"created_ts\", \"updated_ts\"}\n)",
"type UserSetting struct {\n\tUserID int\n\tKey UserSettingKey `json:\"key\"`\n\t// Value is a JSON string with basic value\n\tValue string `json:\"value\"`\n}",
"type UserSettingUpsert struct {",
"\tUserID int `json:\"-\"`",
"\tKey UserSettingKey `json:\"key\"`\n\tValue string `json:\"value\"`\n}",
"func (upsert UserSettingUpsert) Validate() error {\n\tif upsert.Key == UserSettingLocaleKey {\n\t\tlocaleValue := \"en\"\n\t\terr := json.Unmarshal([]byte(upsert.Value), &localeValue)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting locale value\")\n\t\t}\n\t\tif !slices.Contains(UserSettingLocaleValue, localeValue) {\n\t\t\treturn fmt.Errorf(\"invalid user setting locale value\")\n\t\t}\n\t} else if upsert.Key == UserSettingAppearanceKey {\n\t\tappearanceValue := \"system\"\n\t\terr := json.Unmarshal([]byte(upsert.Value), &appearanceValue)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting appearance value\")\n\t\t}\n\t\tif !slices.Contains(UserSettingAppearanceValue, appearanceValue) {\n\t\t\treturn fmt.Errorf(\"invalid user setting appearance value\")\n\t\t}\n\t} else if upsert.Key == UserSettingMemoVisibilityKey {\n\t\tmemoVisibilityValue := Private\n\t\terr := json.Unmarshal([]byte(upsert.Value), &memoVisibilityValue)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting memo visibility value\")\n\t\t}\n\t\tif !slices.Contains(UserSettingMemoVisibilityValue, memoVisibilityValue) {\n\t\t\treturn fmt.Errorf(\"invalid user setting memo visibility value\")\n\t\t}\n\t} else if upsert.Key == UserSettingMemoDisplayTsOptionKey {\n\t\tmemoDisplayTsOption := \"created_ts\"\n\t\terr := json.Unmarshal([]byte(upsert.Value), &memoDisplayTsOption)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal user setting memo display ts option\")\n\t\t}\n\t\tif !slices.Contains(UserSettingMemoDisplayTsOptionKeyValue, memoDisplayTsOption) {\n\t\t\treturn fmt.Errorf(\"invalid user setting memo display ts option value\")\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"invalid user setting key\")\n\t}",
"\treturn nil\n}",
"type UserSettingFind struct {\n\tUserID int",
"\tKey *UserSettingKey `json:\"key\"`\n}",
"type UserSettingDelete struct {\n\tUserID int\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n\t\"golang.org/x/crypto/bcrypt\"\n)",
"func (s *Server) registerAuthRoutes(g *echo.Group) {\n\tg.POST(\"/auth/signin\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tsignin := &api.Signin{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(signin); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted signin request\").SetInternal(err)\n\t\t}",
"\t\tuserFind := &api.UserFind{\n\t\t\tUsername: &signin.Username,\n\t\t}\n\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find user by username %s\", signin.Username)).SetInternal(err)\n\t\t}\n\t\tif user == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf(\"User not found with username %s\", signin.Username))\n\t\t} else if user.RowStatus == api.Archived {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf(\"User has been archived with username %s\", signin.Username))\n\t\t}",
"\t\t// Compare the stored hashed password, with the hashed version of the password that was received.\n\t\tif err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(signin.Password)); err != nil {\n\t\t\t// If the two passwords don't match, return a 401 status.\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Incorrect password\").SetInternal(err)\n\t\t}",
"\t\tif err = setUserSession(c, user); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to set signin session\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user signed in\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/auth/logout\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\terr := removeUserSession(c)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to set logout session\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user logout\",\n\t\t})",
"\t\tc.Response().WriteHeader(http.StatusOK)\n\t\treturn nil\n\t})",
"\tg.POST(\"/auth/signup\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tsignup := &api.Signup{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(signup); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted signup request\").SetInternal(err)\n\t\t}",
"\t\thostUserType := api.Host\n\t\thostUserFind := api.UserFind{\n\t\t\tRole: &hostUserType,\n\t\t}\n\t\thostUser, err := s.Store.FindUser(ctx, &hostUserFind)\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find host user\").SetInternal(err)\n\t\t}\n\t\tif signup.Role == api.Host && hostUser != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Site Host existed, please contact the site host to signin account firstly.\").SetInternal(err)",
"\t\t}",
"\t\tsystemSettingAllowSignUpName := api.SystemSettingAllowSignUpName\n\t\tallowSignUpSetting, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{\n\t\t\tName: &systemSettingAllowSignUpName,\n\t\t})\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find system setting\").SetInternal(err)\n\t\t}",
"\t\tallowSignUpSettingValue := false\n\t\tif allowSignUpSetting != nil {\n\t\t\terr = json.Unmarshal([]byte(allowSignUpSetting.Value), &allowSignUpSettingValue)\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to unmarshal system setting allow signup\").SetInternal(err)\n\t\t\t}\n\t\t}\n\t\tif !allowSignUpSettingValue && hostUser != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Site Host existed, please contact the site host to signin account firstly.\").SetInternal(err)",
"\t\t}",
"\t\tuserCreate := &api.UserCreate{\n\t\t\tUsername: signup.Username,\n\t\t\tRole: api.Role(signup.Role),\n\t\t\tNickname: signup.Username,\n\t\t\tPassword: signup.Password,\n\t\t\tOpenID: common.GenUUID(),\n\t\t}\n\t\tif err := userCreate.Validate(); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user create format.\").SetInternal(err)",
"\t\t}",
"\t\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to generate password hash\").SetInternal(err)\n\t\t}",
"\t\tuserCreate.PasswordHash = string(passwordHash)",
"\t\tuser, err := s.Store.CreateUser(ctx, userCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create user\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user signed up\",\n\t\t})",
"\t\terr = setUserSession(c, user)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to set signup session\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode created user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})\n}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n\t\"golang.org/x/crypto/bcrypt\"\n)",
"func (s *Server) registerAuthRoutes(g *echo.Group) {\n\tg.POST(\"/auth/signin\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tsignin := &api.Signin{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(signin); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted signin request\").SetInternal(err)\n\t\t}",
"\t\tuserFind := &api.UserFind{\n\t\t\tUsername: &signin.Username,\n\t\t}\n\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find user by username %s\", signin.Username)).SetInternal(err)\n\t\t}\n\t\tif user == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf(\"User not found with username %s\", signin.Username))\n\t\t} else if user.RowStatus == api.Archived {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf(\"User has been archived with username %s\", signin.Username))\n\t\t}",
"\t\t// Compare the stored hashed password, with the hashed version of the password that was received.\n\t\tif err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(signin.Password)); err != nil {\n\t\t\t// If the two passwords don't match, return a 401 status.\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Incorrect password\").SetInternal(err)\n\t\t}",
"\t\tif err = setUserSession(c, user); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to set signin session\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user signed in\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/auth/logout\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\terr := removeUserSession(c)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to set logout session\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user logout\",\n\t\t})",
"\t\tc.Response().WriteHeader(http.StatusOK)\n\t\treturn nil\n\t})",
"\tg.POST(\"/auth/signup\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tsignup := &api.Signup{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(signup); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted signup request\").SetInternal(err)\n\t\t}",
"\t\thostUserType := api.Host\n\t\thostUserFind := api.UserFind{\n\t\t\tRole: &hostUserType,\n\t\t}\n\t\thostUser, err := s.Store.FindUser(ctx, &hostUserFind)\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find host user\").SetInternal(err)\n\t\t}\n\t\tif signup.Role == api.Host && hostUser != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Site Host existed, please contact the site host to signin account firstly\").SetInternal(err)",
"\t\t}",
"\t\tsystemSettingAllowSignUpName := api.SystemSettingAllowSignUpName\n\t\tallowSignUpSetting, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{\n\t\t\tName: &systemSettingAllowSignUpName,\n\t\t})\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find system setting\").SetInternal(err)\n\t\t}",
"\t\tallowSignUpSettingValue := false\n\t\tif allowSignUpSetting != nil {\n\t\t\terr = json.Unmarshal([]byte(allowSignUpSetting.Value), &allowSignUpSettingValue)\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to unmarshal system setting allow signup\").SetInternal(err)\n\t\t\t}\n\t\t}\n\t\tif !allowSignUpSettingValue && hostUser != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Site Host existed, please contact the site host to signin account firstly\").SetInternal(err)",
"\t\t}",
"\t\tuserCreate := &api.UserCreate{\n\t\t\tUsername: signup.Username,\n\t\t\tRole: api.Role(signup.Role),\n\t\t\tNickname: signup.Username,\n\t\t\tPassword: signup.Password,\n\t\t\tOpenID: common.GenUUID(),\n\t\t}\n\t\tif err := userCreate.Validate(); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user create format\").SetInternal(err)",
"\t\t}",
"\t\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to generate password hash\").SetInternal(err)\n\t\t}",
"\t\tuserCreate.PasswordHash = string(passwordHash)",
"\t\tuser, err := s.Store.CreateUser(ctx, userCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create user\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user signed up\",\n\t\t})",
"\t\terr = setUserSession(c, user)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to set signup session\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode created user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerMemoRoutes(g *echo.Group) {\n\tg.POST(\"/memo\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n",
"\t\tmemoCreate := &api.MemoCreate{\n\t\t\tCreatorID: userID,\n\t\t}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoCreate); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post memo request\").SetInternal(err)\n\t\t}\n\t\tif memoCreate.Content == \"\" {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Memo content shouldn't be empty\")\n\t\t}",
"\t\tif memoCreate.Visibility == \"\" {\n\t\t\tuserSettingMemoVisibilityKey := api.UserSettingMemoVisibilityKey\n\t\t\tuserMemoVisibilitySetting, err := s.Store.FindUserSetting(ctx, &api.UserSettingFind{\n\t\t\t\tUserID: userID,\n\t\t\t\tKey: &userSettingMemoVisibilityKey,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user setting\").SetInternal(err)\n\t\t\t}",
"\t\t\tif userMemoVisibilitySetting != nil {\n\t\t\t\tmemoVisibility := api.Private\n\t\t\t\terr := json.Unmarshal([]byte(userMemoVisibilitySetting.Value), &memoVisibility)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to unmarshal user setting value\").SetInternal(err)\n\t\t\t\t}\n\t\t\t\tmemoCreate.Visibility = memoVisibility\n\t\t\t} else {\n\t\t\t\t// Private is the default memo visibility.\n\t\t\t\tmemoCreate.Visibility = api.Private\n\t\t\t}\n\t\t}\n",
"",
"\t\tmemo, err := s.Store.CreateMemo(ctx, memoCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create memo\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"memo created\",\n\t\t})",
"\t\tfor _, resourceID := range memoCreate.ResourceIDList {\n\t\t\tif _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{\n\t\t\t\tMemoID: memo.ID,\n\t\t\t\tResourceID: resourceID,\n\t\t\t}); err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo resource\").SetInternal(err)\n\t\t\t}\n\t\t}",
"\t\tmemo, err = s.Store.ComposeMemo(ctx, memo)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to compose memo\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/memo/:memoId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}\n",
"\t\tmemoFind := &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tif _, err := s.Store.FindMemo(ctx, memoFind); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo\").SetInternal(err)",
"",
"\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tmemoPatch := &api.MemoPatch{\n\t\t\tID: memoID,\n\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoPatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch memo request\").SetInternal(err)\n\t\t}\n",
"\t\tmemo, err := s.Store.PatchMemo(ctx, memoPatch)",
"\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch memo\").SetInternal(err)\n\t\t}",
"\t\tfor _, resourceID := range memoPatch.ResourceIDList {\n\t\t\tif _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{\n\t\t\t\tMemoID: memo.ID,\n\t\t\t\tResourceID: resourceID,\n\t\t\t}); err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo resource\").SetInternal(err)\n\t\t\t}\n\t\t}",
"\t\tmemo, err = s.Store.ComposeMemo(ctx, memo)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to compose memo\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoFind := &api.MemoFind{}\n\t\tif userID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &userID\n\t\t}",
"\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tif memoFind.CreatorID == nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find memo\")\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tif memoFind.CreatorID == nil {\n\t\t\t\tmemoFind.CreatorID = ¤tUserID\n\t\t\t} else {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t\t}\n\t\t}",
"\t\trowStatus := api.RowStatus(c.QueryParam(\"rowStatus\"))\n\t\tif rowStatus != \"\" {\n\t\t\tmemoFind.RowStatus = &rowStatus\n\t\t}\n\t\tpinnedStr := c.QueryParam(\"pinned\")\n\t\tif pinnedStr != \"\" {\n\t\t\tpinned := pinnedStr == \"true\"\n\t\t\tmemoFind.Pinned = &pinned\n\t\t}\n\t\ttag := c.QueryParam(\"tag\")\n\t\tif tag != \"\" {",
"\t\t\tcontentSearch := \"#\" + tag + \" \"",
"\t\t\tmemoFind.ContentSearch = &contentSearch\n\t\t}\n\t\tvisibilityListStr := c.QueryParam(\"visibility\")\n\t\tif visibilityListStr != \"\" {\n\t\t\tvisibilityList := []api.Visibility{}\n\t\t\tfor _, visibility := range strings.Split(visibilityListStr, \",\") {\n\t\t\t\tvisibilityList = append(visibilityList, api.Visibility(visibility))\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = visibilityList\n\t\t}\n\t\tif limit, err := strconv.Atoi(c.QueryParam(\"limit\")); err == nil {\n\t\t\tmemoFind.Limit = limit\n\t\t}\n\t\tif offset, err := strconv.Atoi(c.QueryParam(\"offset\")); err == nil {\n\t\t\tmemoFind.Offset = offset\n\t\t}",
"\t\tlist, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch memo list\").SetInternal(err)\n\t\t}",
"\t\tvar pinnedMemoList []*api.Memo\n\t\tvar unpinnedMemoList []*api.Memo",
"\t\tfor _, memo := range list {\n\t\t\tif memo.Pinned {\n\t\t\t\tpinnedMemoList = append(pinnedMemoList, memo)\n\t\t\t} else {\n\t\t\t\tunpinnedMemoList = append(unpinnedMemoList, memo)\n\t\t\t}\n\t\t}",
"\t\tsort.Slice(pinnedMemoList, func(i, j int) bool {\n\t\t\treturn pinnedMemoList[i].DisplayTs > pinnedMemoList[j].DisplayTs\n\t\t})\n\t\tsort.Slice(unpinnedMemoList, func(i, j int) bool {\n\t\t\treturn unpinnedMemoList[i].DisplayTs > unpinnedMemoList[j].DisplayTs\n\t\t})",
"\t\tmemoList := []*api.Memo{}\n\t\tmemoList = append(memoList, pinnedMemoList...)\n\t\tmemoList = append(memoList, unpinnedMemoList...)",
"\t\tif memoFind.Limit != 0 {\n\t\t\tmemoList = memoList[memoFind.Offset:common.Min(len(memoList), memoFind.Offset+memoFind.Limit)]\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memoList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo list response\").SetInternal(err)",
"",
"\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/amount\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tnormalRowStatus := api.Normal\n\t\tmemoFind := &api.MemoFind{\n\t\t\tRowStatus: &normalRowStatus,\n\t\t}\n\t\tif userID, err := strconv.Atoi(c.QueryParam(\"userId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &userID\n\t\t}",
"\t\tmemoList, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(len(memoList))); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo amount\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/stats\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tnormalStatus := api.Normal\n\t\tmemoFind := &api.MemoFind{\n\t\t\tRowStatus: &normalStatus,\n\t\t}\n\t\tif creatorID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &creatorID\n\t\t}\n\t\tif memoFind.CreatorID == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find memo\")\n\t\t}",
"\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tif *memoFind.CreatorID != currentUserID {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t\t} else {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected, api.Private}\n\t\t\t}\n\t\t}",
"\t\tlist, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch memo list\").SetInternal(err)\n\t\t}",
"\t\tdisplayTsList := []int64{}\n\t\tfor _, memo := range list {\n\t\t\tdisplayTsList = append(displayTsList, memo.DisplayTs)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(displayTsList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo stats response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/all\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoFind := &api.MemoFind{}",
"\t\t_, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t}",
"\t\tpinnedStr := c.QueryParam(\"pinned\")\n\t\tif pinnedStr != \"\" {\n\t\t\tpinned := pinnedStr == \"true\"\n\t\t\tmemoFind.Pinned = &pinned\n\t\t}\n\t\ttag := c.QueryParam(\"tag\")\n\t\tif tag != \"\" {\n\t\t\tcontentSearch := \"#\" + tag + \" \"\n\t\t\tmemoFind.ContentSearch = &contentSearch\n\t\t}\n\t\tvisibilityListStr := c.QueryParam(\"visibility\")\n\t\tif visibilityListStr != \"\" {\n\t\t\tvisibilityList := []api.Visibility{}\n\t\t\tfor _, visibility := range strings.Split(visibilityListStr, \",\") {\n\t\t\t\tvisibilityList = append(visibilityList, api.Visibility(visibility))\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = visibilityList\n\t\t}\n\t\tif limit, err := strconv.Atoi(c.QueryParam(\"limit\")); err == nil {\n\t\t\tmemoFind.Limit = limit\n\t\t}\n\t\tif offset, err := strconv.Atoi(c.QueryParam(\"offset\")); err == nil {\n\t\t\tmemoFind.Offset = offset\n\t\t}",
"\t\t// Only fetch normal status memos.\n\t\tnormalStatus := api.Normal\n\t\tmemoFind.RowStatus = &normalStatus",
"\t\tlist, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch all memo list\").SetInternal(err)\n\t\t}",
"\t\tsort.Slice(list, func(i, j int) bool {\n\t\t\treturn list[i].DisplayTs > list[j].DisplayTs\n\t\t})",
"\t\tif memoFind.Limit != 0 {\n\t\t\tlist = list[memoFind.Offset:common.Min(len(list), memoFind.Offset+memoFind.Limit)]\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(list)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode all memo list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})\n",
"\tg.GET(\"/memo/:memoId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)",
"\t\t}",
"\t\tmemoFind := &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t}\n\t\tmemo, err := s.Store.FindMemo(ctx, memoFind)\n\t\tif err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Memo ID not found: %d\", memoID)).SetInternal(err)\n\t\t\t}",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find memo by ID: %v\", memoID)).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif memo.Visibility == api.Private {\n\t\t\tif !ok || memo.CreatorID != userID {\n\t\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"this memo is private only\")\n\t\t\t}\n\t\t} else if memo.Visibility == api.Protected {\n\t\t\tif !ok {\n\t\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"this memo is protected, missing user in session\")\n\t\t\t}\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/memo/:memoId/organizer\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tmemoOrganizerUpsert := &api.MemoOrganizerUpsert{\n\t\t\tMemoID: memoID,\n\t\t\tUserID: userID,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoOrganizerUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post memo organizer request\").SetInternal(err)\n\t\t}",
"\t\terr = s.Store.UpsertMemoOrganizer(ctx, memoOrganizerUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo organizer\").SetInternal(err)",
"\t\t}",
"\t\tmemo, err := s.Store.FindMemo(ctx, &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t})\n\t\tif err != nil {",
"",
"\t\t\tif common.ErrorCode(err) == common.NotFound {",
"\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Memo ID not found: %d\", memoID)).SetInternal(err)\n\t\t\t}",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find memo by ID: %v\", memoID)).SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/memo/:memoId/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tmemoResourceUpsert := &api.MemoResourceUpsert{\n\t\t\tMemoID: memoID,\n\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoResourceUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post memo resource request\").SetInternal(err)\n\t\t}",
"\t\tif _, err := s.Store.UpsertMemoResource(ctx, memoResourceUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo resource\").SetInternal(err)\n\t\t}",
"\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &memoResourceUpsert.ResourceID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/:memoId/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tresourceFind := &api.ResourceFind{\n\t\t\tMemoID: &memoID,\n\t\t}\n\t\tresourceList, err := s.Store.FindResourceList(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resourceList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource list response\").SetInternal(err)\n\t\t}\n\t\treturn nil",
"\t})",
"\tg.DELETE(\"/memo/:memoId/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Memo ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Resource ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)",
"",
"\t\t}",
"\t\tmemoResourceDelete := &api.MemoResourceDelete{\n\t\t\tMemoID: &memoID,\n\t\t\tResourceID: &resourceID,\n\t\t}\n\t\tif err := s.Store.DeleteMemoResource(ctx, memoResourceDelete); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource list\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})",
"\n\tg.DELETE(\"/memo/:memoId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tmemoFind := &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tif _, err := s.Store.FindMemo(ctx, memoFind); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo\").SetInternal(err)\n\t\t}",
"\t\tmemoDelete := &api.MemoDelete{\n\t\t\tID: memoID,\n\t\t}\n\t\tif err := s.Store.DeleteMemo(ctx, memoDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Memo ID not found: %d\", memoID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to delete memo ID: %v\", memoID)).SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})",
"}"
] |
[
1,
1,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
0,
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,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
0,
1,
0,
1,
1,
1,
0,
0,
0,
0,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerMemoRoutes(g *echo.Group) {\n\tg.POST(\"/memo\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n",
"\t\tmemoCreate := &api.MemoCreate{}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoCreate); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post memo request\").SetInternal(err)\n\t\t}\n\t\tif memoCreate.Content == \"\" {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Memo content shouldn't be empty\")\n\t\t}",
"\t\tif memoCreate.Visibility == \"\" {\n\t\t\tuserSettingMemoVisibilityKey := api.UserSettingMemoVisibilityKey\n\t\t\tuserMemoVisibilitySetting, err := s.Store.FindUserSetting(ctx, &api.UserSettingFind{\n\t\t\t\tUserID: userID,\n\t\t\t\tKey: &userSettingMemoVisibilityKey,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user setting\").SetInternal(err)\n\t\t\t}",
"\t\t\tif userMemoVisibilitySetting != nil {\n\t\t\t\tmemoVisibility := api.Private\n\t\t\t\terr := json.Unmarshal([]byte(userMemoVisibilitySetting.Value), &memoVisibility)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to unmarshal user setting value\").SetInternal(err)\n\t\t\t\t}\n\t\t\t\tmemoCreate.Visibility = memoVisibility\n\t\t\t} else {\n\t\t\t\t// Private is the default memo visibility.\n\t\t\t\tmemoCreate.Visibility = api.Private\n\t\t\t}\n\t\t}\n",
"\t\tmemoCreate.CreatorID = userID",
"\t\tmemo, err := s.Store.CreateMemo(ctx, memoCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create memo\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"memo created\",\n\t\t})",
"\t\tfor _, resourceID := range memoCreate.ResourceIDList {\n\t\t\tif _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{\n\t\t\t\tMemoID: memo.ID,\n\t\t\t\tResourceID: resourceID,\n\t\t\t}); err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo resource\").SetInternal(err)\n\t\t\t}\n\t\t}",
"\t\tmemo, err = s.Store.ComposeMemo(ctx, memo)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to compose memo\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/memo/:memoId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}\n",
"\t\tmemo, err := s.Store.FindMemo(ctx, &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t})\n\t\tif err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo\").SetInternal(err)",
"\t\t}\n\t\tif memo.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")",
"\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tmemoPatch := &api.MemoPatch{\n\t\t\tID: memoID,\n\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoPatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch memo request\").SetInternal(err)\n\t\t}\n",
"\t\tmemo, err = s.Store.PatchMemo(ctx, memoPatch)",
"\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch memo\").SetInternal(err)\n\t\t}",
"\t\tfor _, resourceID := range memoPatch.ResourceIDList {\n\t\t\tif _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{\n\t\t\t\tMemoID: memo.ID,\n\t\t\t\tResourceID: resourceID,\n\t\t\t}); err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo resource\").SetInternal(err)\n\t\t\t}\n\t\t}",
"\t\tmemo, err = s.Store.ComposeMemo(ctx, memo)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to compose memo\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoFind := &api.MemoFind{}\n\t\tif userID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &userID\n\t\t}",
"\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tif memoFind.CreatorID == nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find memo\")\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tif memoFind.CreatorID == nil {\n\t\t\t\tmemoFind.CreatorID = ¤tUserID\n\t\t\t} else {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t\t}\n\t\t}",
"\t\trowStatus := api.RowStatus(c.QueryParam(\"rowStatus\"))\n\t\tif rowStatus != \"\" {\n\t\t\tmemoFind.RowStatus = &rowStatus\n\t\t}\n\t\tpinnedStr := c.QueryParam(\"pinned\")\n\t\tif pinnedStr != \"\" {\n\t\t\tpinned := pinnedStr == \"true\"\n\t\t\tmemoFind.Pinned = &pinned\n\t\t}\n\t\ttag := c.QueryParam(\"tag\")\n\t\tif tag != \"\" {",
"\t\t\tcontentSearch := \"#\" + tag",
"\t\t\tmemoFind.ContentSearch = &contentSearch\n\t\t}\n\t\tvisibilityListStr := c.QueryParam(\"visibility\")\n\t\tif visibilityListStr != \"\" {\n\t\t\tvisibilityList := []api.Visibility{}\n\t\t\tfor _, visibility := range strings.Split(visibilityListStr, \",\") {\n\t\t\t\tvisibilityList = append(visibilityList, api.Visibility(visibility))\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = visibilityList\n\t\t}\n\t\tif limit, err := strconv.Atoi(c.QueryParam(\"limit\")); err == nil {\n\t\t\tmemoFind.Limit = limit\n\t\t}\n\t\tif offset, err := strconv.Atoi(c.QueryParam(\"offset\")); err == nil {\n\t\t\tmemoFind.Offset = offset\n\t\t}",
"\t\tlist, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch memo list\").SetInternal(err)\n\t\t}",
"\t\tvar pinnedMemoList []*api.Memo\n\t\tvar unpinnedMemoList []*api.Memo",
"\t\tfor _, memo := range list {\n\t\t\tif memo.Pinned {\n\t\t\t\tpinnedMemoList = append(pinnedMemoList, memo)\n\t\t\t} else {\n\t\t\t\tunpinnedMemoList = append(unpinnedMemoList, memo)\n\t\t\t}\n\t\t}",
"\t\tsort.Slice(pinnedMemoList, func(i, j int) bool {\n\t\t\treturn pinnedMemoList[i].DisplayTs > pinnedMemoList[j].DisplayTs\n\t\t})\n\t\tsort.Slice(unpinnedMemoList, func(i, j int) bool {\n\t\t\treturn unpinnedMemoList[i].DisplayTs > unpinnedMemoList[j].DisplayTs\n\t\t})",
"\t\tmemoList := []*api.Memo{}\n\t\tmemoList = append(memoList, pinnedMemoList...)\n\t\tmemoList = append(memoList, unpinnedMemoList...)",
"\t\tif memoFind.Limit != 0 {\n\t\t\tmemoList = memoList[memoFind.Offset:common.Min(len(memoList), memoFind.Offset+memoFind.Limit)]\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memoList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo list response\").SetInternal(err)",
"\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/:memoId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tmemoFind := &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t}\n\t\tmemo, err := s.Store.FindMemo(ctx, memoFind)\n\t\tif err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Memo ID not found: %d\", memoID)).SetInternal(err)\n\t\t\t}",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find memo by ID: %v\", memoID)).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif memo.Visibility == api.Private {\n\t\t\tif !ok || memo.CreatorID != userID {\n\t\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"this memo is private only\")\n\t\t\t}\n\t\t} else if memo.Visibility == api.Protected {\n\t\t\tif !ok {\n\t\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"this memo is protected, missing user in session\")\n\t\t\t}\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/memo/:memoId/organizer\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tmemoOrganizerUpsert := &api.MemoOrganizerUpsert{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoOrganizerUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post memo organizer request\").SetInternal(err)\n\t\t}\n\t\tmemoOrganizerUpsert.MemoID = memoID\n\t\tmemoOrganizerUpsert.UserID = userID",
"\t\terr = s.Store.UpsertMemoOrganizer(ctx, memoOrganizerUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo organizer\").SetInternal(err)\n\t\t}",
"\t\tmemo, err := s.Store.FindMemo(ctx, &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t})\n\t\tif err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Memo ID not found: %d\", memoID)).SetInternal(err)\n\t\t\t}",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to find memo by ID: %v\", memoID)).SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(memo)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/memo/:memoId/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tmemoResourceUpsert := &api.MemoResourceUpsert{\n\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(memoResourceUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post memo resource request\").SetInternal(err)\n\t\t}\n\t\tmemoResourceUpsert.MemoID = memoID",
"\t\tif _, err := s.Store.UpsertMemoResource(ctx, memoResourceUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert memo resource\").SetInternal(err)\n\t\t}",
"\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &memoResourceUpsert.ResourceID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/:memoId/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}",
"\t\tresourceFind := &api.ResourceFind{\n\t\t\tMemoID: &memoID,\n\t\t}\n\t\tresourceList, err := s.Store.FindResourceList(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resourceList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource list response\").SetInternal(err)",
"\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/amount\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tnormalRowStatus := api.Normal\n\t\tmemoFind := &api.MemoFind{\n\t\t\tRowStatus: &normalRowStatus,\n\t\t}\n\t\tif userID, err := strconv.Atoi(c.QueryParam(\"userId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &userID\n\t\t}",
"\t\tmemoList, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(len(memoList))); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo amount\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/stats\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tnormalStatus := api.Normal\n\t\tmemoFind := &api.MemoFind{\n\t\t\tRowStatus: &normalStatus,\n\t\t}\n\t\tif creatorID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &creatorID\n\t\t}\n\t\tif memoFind.CreatorID == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find memo\")\n\t\t}",
"\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tif *memoFind.CreatorID != currentUserID {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t\t} else {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected, api.Private}\n\t\t\t}\n\t\t}",
"\t\tlist, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch memo list\").SetInternal(err)\n\t\t}",
"\t\tdisplayTsList := []int64{}\n\t\tfor _, memo := range list {\n\t\t\tdisplayTsList = append(displayTsList, memo.DisplayTs)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(displayTsList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode memo stats response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/memo/all\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tmemoFind := &api.MemoFind{}",
"\t\t_, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t}",
"\t\tpinnedStr := c.QueryParam(\"pinned\")\n\t\tif pinnedStr != \"\" {\n\t\t\tpinned := pinnedStr == \"true\"\n\t\t\tmemoFind.Pinned = &pinned\n\t\t}\n\t\ttag := c.QueryParam(\"tag\")\n\t\tif tag != \"\" {\n\t\t\tcontentSearch := \"#\" + tag + \" \"\n\t\t\tmemoFind.ContentSearch = &contentSearch\n\t\t}\n\t\tvisibilityListStr := c.QueryParam(\"visibility\")\n\t\tif visibilityListStr != \"\" {\n\t\t\tvisibilityList := []api.Visibility{}\n\t\t\tfor _, visibility := range strings.Split(visibilityListStr, \",\") {\n\t\t\t\tvisibilityList = append(visibilityList, api.Visibility(visibility))\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = visibilityList\n\t\t}\n\t\tif limit, err := strconv.Atoi(c.QueryParam(\"limit\")); err == nil {\n\t\t\tmemoFind.Limit = limit\n\t\t}\n\t\tif offset, err := strconv.Atoi(c.QueryParam(\"offset\")); err == nil {\n\t\t\tmemoFind.Offset = offset\n\t\t}",
"\t\t// Only fetch normal status memos.\n\t\tnormalStatus := api.Normal\n\t\tmemoFind.RowStatus = &normalStatus",
"\t\tlist, err := s.Store.FindMemoList(ctx, memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch all memo list\").SetInternal(err)\n\t\t}",
"\t\tsort.Slice(list, func(i, j int) bool {\n\t\t\treturn list[i].DisplayTs > list[j].DisplayTs\n\t\t})",
"\t\tif memoFind.Limit != 0 {\n\t\t\tlist = list[memoFind.Offset:common.Min(len(list), memoFind.Offset+memoFind.Limit)]\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(list)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode all memo list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})\n",
"\tg.DELETE(\"/memo/:memoId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)",
"",
"\t\t}",
"\t\tmemo, err := s.Store.FindMemo(ctx, &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t})\n\t\tif err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo\").SetInternal(err)\n\t\t}\n\t\tif memo.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")\n\t\t}",
"\t\tmemoDelete := &api.MemoDelete{\n\t\t\tID: memoID,\n\t\t}\n\t\tif err := s.Store.DeleteMemo(ctx, memoDelete); err != nil {",
"\t\t\tif common.ErrorCode(err) == common.NotFound {",
"\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Memo ID not found: %d\", memoID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to delete memo ID: %v\", memoID)).SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)",
"\t})",
"\tg.DELETE(\"/memo/:memoId/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tmemoID, err := strconv.Atoi(c.Param(\"memoId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Memo ID is not a number: %s\", c.Param(\"memoId\"))).SetInternal(err)\n\t\t}\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Resource ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)",
"\t\t}",
"\t\tmemo, err := s.Store.FindMemo(ctx, &api.MemoFind{\n\t\t\tID: &memoID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo\").SetInternal(err)\n\t\t}\n\t\tif memo.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")",
"\t\t}",
"\t\tmemoResourceDelete := &api.MemoResourceDelete{\n\t\t\tMemoID: &memoID,\n\t\t\tResourceID: &resourceID,\n\t\t}\n\t\tif err := s.Store.DeleteMemoResource(ctx, memoResourceDelete); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource list\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})",
"",
"}"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"const (\n\t// The max file size is 32MB.\n\tmaxFileSize = (32 * 8) << 20\n)",
"func (s *Server) registerResourceRoutes(g *echo.Group) {\n\tg.POST(\"/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tif err := c.Request().ParseMultipartForm(maxFileSize); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Upload file overload max size\").SetInternal(err)\n\t\t}",
"\t\tfile, err := c.FormFile(\"file\")\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to get uploading file\").SetInternal(err)\n\t\t}\n\t\tif file == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Upload file not found\").SetInternal(err)\n\t\t}",
"\t\tfilename := file.Filename\n\t\tfiletype := file.Header.Get(\"Content-Type\")\n\t\tsize := file.Size\n\t\tsrc, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to open file\").SetInternal(err)\n\t\t}\n\t\tdefer src.Close()",
"\t\tfileBytes, err := io.ReadAll(src)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to read file\").SetInternal(err)\n\t\t}",
"\t\tresourceCreate := &api.ResourceCreate{",
"",
"\t\t\tFilename: filename,\n\t\t\tType: filetype,\n\t\t\tSize: size,\n\t\t\tBlob: fileBytes,",
"\t\t\tCreatorID: userID,\n\t\t}\n",
"\t\tresource, err := s.Store.CreateResource(ctx, resourceCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create resource\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"resource created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tlist, err := s.Store.FindResourceList(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource list\").SetInternal(err)\n\t\t}",
"\t\tfor _, resource := range list {\n\t\t\tmemoResourceList, err := s.Store.FindMemoResourceList(ctx, &api.MemoResourceFind{\n\t\t\t\tResourceID: &resource.ID,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo resource list\").SetInternal(err)\n\t\t\t}\n\t\t\tresource.LinkedMemoAmount = len(memoResourceList)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(list)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/resource/:resourceId/blob\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Writer.WriteHeader(http.StatusOK)\n\t\tc.Response().Writer.Header().Set(\"Content-Type\", resource.Type)",
"",
"\t\tif _, err := c.Response().Writer.Write(resource.Blob); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to write resource blob\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tresourceFind := &api.ResourceFind{",
"\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tif _, err := s.Store.FindResource(ctx, resourceFind); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find resource\").SetInternal(err)",
"",
"\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tresourcePatch := &api.ResourcePatch{",
"\t\t\tID: resourceID,",
"\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(resourcePatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch resource request\").SetInternal(err)\n\t\t}\n",
"\t\tresource, err := s.Store.PatchResource(ctx, resourcePatch)",
"\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tresource, err := s.Store.FindResource(ctx, &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find resource\").SetInternal(err)\n\t\t}",
"\t\tif resource == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, \"Not find resource\").SetInternal(err)",
"\t\t}",
"\t\tresourceDelete := &api.ResourceDelete{\n\t\t\tID: resourceID,\n\t\t}\n\t\tif err := s.Store.DeleteResource(ctx, resourceDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Resource ID not found: %d\", resourceID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to delete resource\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})\n}",
"func (s *Server) registerResourcePublicRoutes(g *echo.Group) {\n\tg.GET(\"/r/:resourceId/:filename\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}\n\t\tfilename, err := url.QueryUnescape(c.Param(\"filename\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"filename is invalid: %s\", c.Param(\"filename\"))).SetInternal(err)\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tFilename: &filename,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to fetch resource ID: %v\", resourceID)).SetInternal(err)\n\t\t}",
"\t\tc.Response().Writer.Header().Set(\"Content-Type\", resource.Type)\n\t\tc.Response().Writer.WriteHeader(http.StatusOK)\n\t\tc.Response().Writer.Header().Set(echo.HeaderCacheControl, \"max-age=31536000, immutable\")\n\t\tc.Response().Writer.Header().Set(echo.HeaderContentSecurityPolicy, \"default-src 'self'\")\n\t\tif _, err := c.Response().Writer.Write(resource.Blob); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to write response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})\n}"
] |
[
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,
0,
1,
1,
1,
1,
0,
1,
0,
1,
1,
0,
1,
0,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"const (\n\t// The max file size is 32MB.\n\tmaxFileSize = (32 * 8) << 20\n)",
"func (s *Server) registerResourceRoutes(g *echo.Group) {\n\tg.POST(\"/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tif err := c.Request().ParseMultipartForm(maxFileSize); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Upload file overload max size\").SetInternal(err)\n\t\t}",
"\t\tfile, err := c.FormFile(\"file\")\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to get uploading file\").SetInternal(err)\n\t\t}\n\t\tif file == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Upload file not found\").SetInternal(err)\n\t\t}",
"\t\tfilename := file.Filename\n\t\tfiletype := file.Header.Get(\"Content-Type\")\n\t\tsize := file.Size\n\t\tsrc, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to open file\").SetInternal(err)\n\t\t}\n\t\tdefer src.Close()",
"\t\tfileBytes, err := io.ReadAll(src)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to read file\").SetInternal(err)\n\t\t}",
"\t\tresourceCreate := &api.ResourceCreate{",
"\t\t\tCreatorID: userID,",
"\t\t\tFilename: filename,\n\t\t\tType: filetype,\n\t\t\tSize: size,\n\t\t\tBlob: fileBytes,",
"\t\t}",
"\t\tresource, err := s.Store.CreateResource(ctx, resourceCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create resource\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"resource created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/resource\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tlist, err := s.Store.FindResourceList(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource list\").SetInternal(err)\n\t\t}",
"\t\tfor _, resource := range list {\n\t\t\tmemoResourceList, err := s.Store.FindMemoResourceList(ctx, &api.MemoResourceFind{\n\t\t\t\tResourceID: &resource.ID,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo resource list\").SetInternal(err)\n\t\t\t}\n\t\t\tresource.LinkedMemoAmount = len(memoResourceList)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(list)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/resource/:resourceId/blob\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Writer.WriteHeader(http.StatusOK)\n\t\tc.Response().Writer.Header().Set(\"Content-Type\", resource.Type)",
"\t\tc.Response().Writer.Header().Set(echo.HeaderContentSecurityPolicy, \"default-src 'self'\")",
"\t\tif _, err := c.Response().Writer.Write(resource.Blob); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to write resource blob\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tresourceFind := &api.ResourceFind{",
"\t\t\tID: &resourceID,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find resource\").SetInternal(err)",
"\t\t}\n\t\tif resource.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")",
"\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tresourcePatch := &api.ResourcePatch{",
"",
"\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(resourcePatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch resource request\").SetInternal(err)\n\t\t}\n",
"\t\tresource.ID = resourceID\n\t\tresource, err = s.Store.PatchResource(ctx, resourcePatch)",
"\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch resource\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(resource)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode resource response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/resource/:resourceId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}",
"\t\tresource, err := s.Store.FindResource(ctx, &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tCreatorID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find resource\").SetInternal(err)\n\t\t}",
"\t\tif resource.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")",
"\t\t}",
"\t\tresourceDelete := &api.ResourceDelete{\n\t\t\tID: resourceID,\n\t\t}\n\t\tif err := s.Store.DeleteResource(ctx, resourceDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Resource ID not found: %d\", resourceID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to delete resource\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})\n}",
"func (s *Server) registerResourcePublicRoutes(g *echo.Group) {\n\tg.GET(\"/r/:resourceId/:filename\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tresourceID, err := strconv.Atoi(c.Param(\"resourceId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"resourceId\"))).SetInternal(err)\n\t\t}\n\t\tfilename, err := url.QueryUnescape(c.Param(\"filename\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"filename is invalid: %s\", c.Param(\"filename\"))).SetInternal(err)\n\t\t}\n\t\tresourceFind := &api.ResourceFind{\n\t\t\tID: &resourceID,\n\t\t\tFilename: &filename,\n\t\t}\n\t\tresource, err := s.Store.FindResource(ctx, resourceFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to fetch resource ID: %v\", resourceID)).SetInternal(err)\n\t\t}",
"\t\tc.Response().Writer.Header().Set(\"Content-Type\", resource.Type)\n\t\tc.Response().Writer.WriteHeader(http.StatusOK)\n\t\tc.Response().Writer.Header().Set(echo.HeaderCacheControl, \"max-age=31536000, immutable\")\n\t\tc.Response().Writer.Header().Set(echo.HeaderContentSecurityPolicy, \"default-src 'self'\")\n\t\tif _, err := c.Response().Writer.Write(resource.Blob); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to write response\").SetInternal(err)\n\t\t}\n\t\treturn nil\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerShortcutRoutes(g *echo.Group) {\n\tg.POST(\"/shortcut\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tshortcutCreate := &api.ShortcutCreate{\n\t\t\tCreatorID: userID,\n\t\t}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(shortcutCreate); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post shortcut request\").SetInternal(err)\n\t\t}\n",
"",
"\t\tshortcut, err := s.Store.CreateShortcut(ctx, shortcutCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create shortcut\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"shortcut created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(shortcut)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/shortcut/:shortcutId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"",
"\t\tshortcutID, err := strconv.Atoi(c.Param(\"shortcutId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"shortcutId\"))).SetInternal(err)\n\t\t}\n",
"",
"\t\tcurrentTs := time.Now().Unix()\n\t\tshortcutPatch := &api.ShortcutPatch{",
"\t\t\tID: shortcutID,",
"\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(shortcutPatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch shortcut request\").SetInternal(err)\n\t\t}\n",
"\t\tshortcut, err := s.Store.PatchShortcut(ctx, shortcutPatch)",
"\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch shortcut\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(shortcut)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/shortcut\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tshortcutFind := &api.ShortcutFind{}",
"\t\tif userID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\tshortcutFind.CreatorID = &userID\n\t\t} else {\n\t\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\t\tif !ok {\n\t\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find shortcut\")\n\t\t\t}",
"\t\t\tshortcutFind.CreatorID = &userID",
"\t\t}",
"\t\tlist, err := s.Store.FindShortcutList(ctx, shortcutFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch shortcut list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(list)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/shortcut/:shortcutId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tshortcutID, err := strconv.Atoi(c.Param(\"shortcutId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"shortcutId\"))).SetInternal(err)\n\t\t}",
"\t\tshortcutFind := &api.ShortcutFind{\n\t\t\tID: &shortcutID,\n\t\t}\n\t\tshortcut, err := s.Store.FindShortcut(ctx, shortcutFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to fetch shortcut by ID %d\", *shortcutFind.ID)).SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(shortcut)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/shortcut/:shortcutId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"",
"\t\tshortcutID, err := strconv.Atoi(c.Param(\"shortcutId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"shortcutId\"))).SetInternal(err)",
"",
"\t\t}",
"\t\tshortcutDelete := &api.ShortcutDelete{\n\t\t\tID: &shortcutID,\n\t\t}\n\t\tif err := s.Store.DeleteShortcut(ctx, shortcutDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Shortcut ID not found: %d\", shortcutID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to delete shortcut\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})\n}"
] |
[
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
1,
0,
1,
0,
1,
0,
1,
0,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerShortcutRoutes(g *echo.Group) {\n\tg.POST(\"/shortcut\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tshortcutCreate := &api.ShortcutCreate{}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(shortcutCreate); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post shortcut request\").SetInternal(err)\n\t\t}\n",
"\t\tshortcutCreate.CreatorID = userID",
"\t\tshortcut, err := s.Store.CreateShortcut(ctx, shortcutCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create shortcut\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"shortcut created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(shortcut)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/shortcut/:shortcutId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tshortcutID, err := strconv.Atoi(c.Param(\"shortcutId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"shortcutId\"))).SetInternal(err)\n\t\t}\n",
"\t\tshortcutFind := &api.ShortcutFind{\n\t\t\tID: &shortcutID,\n\t\t}\n\t\tshortcut, err := s.Store.FindShortcut(ctx, shortcutFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find shortcut\").SetInternal(err)\n\t\t}\n\t\tif shortcut.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")\n\t\t}\n",
"\t\tcurrentTs := time.Now().Unix()\n\t\tshortcutPatch := &api.ShortcutPatch{",
"",
"\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(shortcutPatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch shortcut request\").SetInternal(err)\n\t\t}\n",
"\t\tshortcutPatch.ID = shortcutID\n\t\tshortcut, err = s.Store.PatchShortcut(ctx, shortcutPatch)",
"\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch shortcut\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(shortcut)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/shortcut\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find shortcut\")\n\t\t}\n\t\tshortcutFind := &api.ShortcutFind{\n\t\t\tCreatorID: &userID,",
"\t\t}",
"\t\tlist, err := s.Store.FindShortcutList(ctx, shortcutFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch shortcut list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(list)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/shortcut/:shortcutId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tshortcutID, err := strconv.Atoi(c.Param(\"shortcutId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"shortcutId\"))).SetInternal(err)\n\t\t}",
"\t\tshortcutFind := &api.ShortcutFind{\n\t\t\tID: &shortcutID,\n\t\t}\n\t\tshortcut, err := s.Store.FindShortcut(ctx, shortcutFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to fetch shortcut by ID %d\", *shortcutFind.ID)).SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(shortcut)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode shortcut response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/shortcut/:shortcutId\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tshortcutID, err := strconv.Atoi(c.Param(\"shortcutId\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"shortcutId\"))).SetInternal(err)",
"\t\t}",
"\t\tshortcutFind := &api.ShortcutFind{\n\t\t\tID: &shortcutID,\n\t\t}\n\t\tshortcut, err := s.Store.FindShortcut(ctx, shortcutFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find shortcut\").SetInternal(err)\n\t\t}\n\t\tif shortcut.CreatorID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")",
"\t\t}",
"\t\tshortcutDelete := &api.ShortcutDelete{\n\t\t\tID: &shortcutID,\n\t\t}\n\t\tif err := s.Store.DeleteShortcut(ctx, shortcutDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Shortcut ID not found: %d\", shortcutID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to delete shortcut\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"os\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerSystemRoutes(g *echo.Group) {\n\tg.GET(\"/ping\", func(c echo.Context) error {\n\t\tdata := s.Profile",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(data)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to compose system profile\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/status\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\thostUserType := api.Host\n\t\thostUserFind := api.UserFind{\n\t\t\tRole: &hostUserType,\n\t\t}\n\t\thostUser, err := s.Store.FindUser(ctx, &hostUserFind)\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find host user\").SetInternal(err)\n\t\t}",
"\t\tif hostUser != nil {\n\t\t\t// data desensitize\n\t\t\thostUser.OpenID = \"\"\n\t\t\thostUser.Email = \"\"\n\t\t}",
"\t\tsystemStatus := api.SystemStatus{\n\t\t\tHost: hostUser,\n\t\t\tProfile: *s.Profile,\n\t\t\tDBSize: 0,\n\t\t\tAllowSignUp: false,\n\t\t\tAdditionalStyle: \"\",\n\t\t\tAdditionalScript: \"\",\n\t\t\tCustomizedProfile: api.CustomizedProfile{\n\t\t\t\tName: \"memos\",\n\t\t\t\tLogoURL: \"\",\n\t\t\t\tDescription: \"\",\n\t\t\t\tLocale: \"en\",\n\t\t\t\tAppearance: \"system\",\n\t\t\t\tExternalURL: \"\",\n\t\t\t},\n\t\t}",
"\t\tsystemSettingList, err := s.Store.FindSystemSettingList(ctx, &api.SystemSettingFind{})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find system setting list\").SetInternal(err)\n\t\t}\n\t\tfor _, systemSetting := range systemSettingList {\n\t\t\tvar value interface{}\n\t\t\terr := json.Unmarshal([]byte(systemSetting.Value), &value)\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to unmarshal system setting\").SetInternal(err)\n\t\t\t}",
"\t\t\tif systemSetting.Name == api.SystemSettingAllowSignUpName {\n\t\t\t\tsystemStatus.AllowSignUp = value.(bool)\n\t\t\t} else if systemSetting.Name == api.SystemSettingAdditionalStyleName {\n\t\t\t\tsystemStatus.AdditionalStyle = value.(string)\n\t\t\t} else if systemSetting.Name == api.SystemSettingAdditionalScriptName {\n\t\t\t\tsystemStatus.AdditionalScript = value.(string)\n\t\t\t} else if systemSetting.Name == api.SystemSettingCustomizedProfileName {\n\t\t\t\tvalueMap := value.(map[string]interface{})",
"\t\t\t\tsystemStatus.CustomizedProfile = api.CustomizedProfile{\n\t\t\t\t\tName: valueMap[\"name\"].(string),\n\t\t\t\t\tLogoURL: valueMap[\"logoUrl\"].(string),\n\t\t\t\t\tDescription: valueMap[\"description\"].(string),\n\t\t\t\t\tLocale: valueMap[\"locale\"].(string),\n\t\t\t\t\tAppearance: valueMap[\"appearance\"].(string),\n\t\t\t\t\tExternalURL: valueMap[\"externalUrl\"].(string),",
"\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\t// Get database size for host user.\n\t\tif ok {\n\t\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\t\tID: &userID,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t\t}\n\t\t\tif user != nil && user.Role == api.Host {\n\t\t\t\tfi, err := os.Stat(s.Profile.DSN)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to read database fileinfo\").SetInternal(err)\n\t\t\t\t}\n\t\t\t\tsystemStatus.DBSize = fi.Size()\n\t\t\t}\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(systemStatus)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode system status response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/system/setting\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}",
"\t\tif user == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, \"Current signin user not found\")\n\t\t} else if user.Role != api.Host {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")\n\t\t}",
"\t\tsystemSettingUpsert := &api.SystemSettingUpsert{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(systemSettingUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post system setting request\").SetInternal(err)\n\t\t}\n\t\tif err := systemSettingUpsert.Validate(); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"system setting invalidate\").SetInternal(err)\n\t\t}",
"\t\tsystemSetting, err := s.Store.UpsertSystemSetting(ctx, systemSettingUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert system setting\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"systemSetting updated\",\n\t\t\tLabels: map[string]string{\"field\": string(systemSettingUpsert.Name)},\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(systemSetting)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode system setting response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/system/setting\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tsystemSettingList, err := s.Store.FindSystemSettingList(ctx, &api.SystemSettingFind{})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find system setting list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(systemSettingList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode system setting list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/system/vacuum\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}\n\t\tif user == nil || user.Role != api.Host {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")\n\t\t}\n\t\tif err := s.Store.Vacuum(ctx); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to vacuum database\").SetInternal(err)\n\t\t}\n\t\tc.Response().WriteHeader(http.StatusOK)\n\t\treturn nil\n\t})\n}"
] |
[
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"os\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerSystemRoutes(g *echo.Group) {\n\tg.GET(\"/ping\", func(c echo.Context) error {\n\t\tdata := s.Profile",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(data)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to compose system profile\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/status\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\thostUserType := api.Host\n\t\thostUserFind := api.UserFind{\n\t\t\tRole: &hostUserType,\n\t\t}\n\t\thostUser, err := s.Store.FindUser(ctx, &hostUserFind)\n\t\tif err != nil && common.ErrorCode(err) != common.NotFound {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find host user\").SetInternal(err)\n\t\t}",
"\t\tif hostUser != nil {\n\t\t\t// data desensitize\n\t\t\thostUser.OpenID = \"\"\n\t\t\thostUser.Email = \"\"\n\t\t}",
"\t\tsystemStatus := api.SystemStatus{\n\t\t\tHost: hostUser,\n\t\t\tProfile: *s.Profile,\n\t\t\tDBSize: 0,\n\t\t\tAllowSignUp: false,\n\t\t\tAdditionalStyle: \"\",\n\t\t\tAdditionalScript: \"\",\n\t\t\tCustomizedProfile: api.CustomizedProfile{\n\t\t\t\tName: \"memos\",\n\t\t\t\tLogoURL: \"\",\n\t\t\t\tDescription: \"\",\n\t\t\t\tLocale: \"en\",\n\t\t\t\tAppearance: \"system\",\n\t\t\t\tExternalURL: \"\",\n\t\t\t},\n\t\t}",
"\t\tsystemSettingList, err := s.Store.FindSystemSettingList(ctx, &api.SystemSettingFind{})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find system setting list\").SetInternal(err)\n\t\t}\n\t\tfor _, systemSetting := range systemSettingList {\n\t\t\tvar value interface{}\n\t\t\terr := json.Unmarshal([]byte(systemSetting.Value), &value)\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to unmarshal system setting\").SetInternal(err)\n\t\t\t}",
"\t\t\tif systemSetting.Name == api.SystemSettingAllowSignUpName {\n\t\t\t\tsystemStatus.AllowSignUp = value.(bool)\n\t\t\t} else if systemSetting.Name == api.SystemSettingAdditionalStyleName {\n\t\t\t\tsystemStatus.AdditionalStyle = value.(string)\n\t\t\t} else if systemSetting.Name == api.SystemSettingAdditionalScriptName {\n\t\t\t\tsystemStatus.AdditionalScript = value.(string)\n\t\t\t} else if systemSetting.Name == api.SystemSettingCustomizedProfileName {\n\t\t\t\tvalueMap := value.(map[string]interface{})",
"\t\t\t\tsystemStatus.CustomizedProfile = api.CustomizedProfile{}\n\t\t\t\tif v := valueMap[\"name\"]; v != nil {\n\t\t\t\t\tsystemStatus.CustomizedProfile.Name = v.(string)\n\t\t\t\t}\n\t\t\t\tif v := valueMap[\"logoUrl\"]; v != nil {\n\t\t\t\t\tsystemStatus.CustomizedProfile.LogoURL = v.(string)\n\t\t\t\t}\n\t\t\t\tif v := valueMap[\"description\"]; v != nil {\n\t\t\t\t\tsystemStatus.CustomizedProfile.Description = v.(string)\n\t\t\t\t}\n\t\t\t\tif v := valueMap[\"locale\"]; v != nil {\n\t\t\t\t\tsystemStatus.CustomizedProfile.Locale = v.(string)\n\t\t\t\t}\n\t\t\t\tif v := valueMap[\"appearance\"]; v != nil {\n\t\t\t\t\tsystemStatus.CustomizedProfile.Appearance = v.(string)\n\t\t\t\t}\n\t\t\t\tif v := valueMap[\"externalUrl\"]; v != nil {\n\t\t\t\t\tsystemStatus.CustomizedProfile.ExternalURL = v.(string)",
"\t\t\t\t}\n\t\t\t}\n\t\t}",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\t// Get database size for host user.\n\t\tif ok {\n\t\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\t\tID: &userID,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t\t}\n\t\t\tif user != nil && user.Role == api.Host {\n\t\t\t\tfi, err := os.Stat(s.Profile.DSN)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to read database fileinfo\").SetInternal(err)\n\t\t\t\t}\n\t\t\t\tsystemStatus.DBSize = fi.Size()\n\t\t\t}\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(systemStatus)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode system status response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/system/setting\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}",
"\t\tif user == nil || user.Role != api.Host {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")\n\t\t}",
"\t\tsystemSettingUpsert := &api.SystemSettingUpsert{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(systemSettingUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post system setting request\").SetInternal(err)\n\t\t}\n\t\tif err := systemSettingUpsert.Validate(); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"system setting invalidate\").SetInternal(err)\n\t\t}",
"\t\tsystemSetting, err := s.Store.UpsertSystemSetting(ctx, systemSettingUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert system setting\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"systemSetting updated\",\n\t\t\tLabels: map[string]string{\"field\": string(systemSettingUpsert.Name)},\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(systemSetting)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode system setting response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/system/setting\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tsystemSettingList, err := s.Store.FindSystemSettingList(ctx, &api.SystemSettingFind{})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find system setting list\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(systemSettingList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode system setting list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/system/vacuum\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}\n\t\tif user == nil || user.Role != api.Host {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Unauthorized\")\n\t\t}\n\t\tif err := s.Store.Vacuum(ctx); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to vacuum database\").SetInternal(err)\n\t\t}\n\t\tc.Response().WriteHeader(http.StatusOK)\n\t\treturn nil\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerTagRoutes(g *echo.Group) {\n\tg.POST(\"/tag\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n",
"\t\ttagUpsert := &api.TagUpsert{\n\t\t\tCreatorID: userID,\n\t\t}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(tagUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post tag request\").SetInternal(err)\n\t\t}\n\t\tif tagUpsert.Name == \"\" {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Tag name shouldn't be empty\")\n\t\t}\n",
"",
"\t\ttag, err := s.Store.UpsertTag(ctx, tagUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert tag\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"tag created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tag.Name)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode tag response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/tag\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\ttagFind := &api.TagFind{}\n\t\tif userID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\ttagFind.CreatorID = userID\n\t\t}",
"\t\tif tagFind.CreatorID == 0 {\n\t\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\t\tif !ok {\n\t\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find tag\")\n\t\t\t}\n\t\t\ttagFind.CreatorID = currentUserID\n\t\t}",
"\t\ttagList, err := s.Store.FindTagList(ctx, tagFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find tag list\").SetInternal(err)\n\t\t}",
"\t\ttagNameList := []string{}\n\t\tfor _, tag := range tagList {\n\t\t\ttagNameList = append(tagNameList, tag.Name)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tagNameList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode tags response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/tag/suggestion\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"",
"\t\tcontentSearch := \"#\"\n\t\tnormalRowStatus := api.Normal\n\t\tmemoFind := api.MemoFind{",
"",
"\t\t\tContentSearch: &contentSearch,\n\t\t\tRowStatus: &normalRowStatus,",
"\t\t}",
"\t\tif userID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\tmemoFind.CreatorID = &userID\n\t\t}",
"\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\tif memoFind.CreatorID == nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find memo\")\n\t\t\t}\n\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public}\n\t\t} else {\n\t\t\tif memoFind.CreatorID == nil {\n\t\t\t\tmemoFind.CreatorID = ¤tUserID\n\t\t\t} else {\n\t\t\t\tmemoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}\n\t\t\t}",
"\t\t}",
"\t\tmemoList, err := s.Store.FindMemoList(ctx, &memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo list\").SetInternal(err)\n\t\t}",
"\t\ttagMapSet := make(map[string]bool)\n\t\tfor _, memo := range memoList {\n\t\t\tfor _, tag := range findTagListFromMemoContent(memo.Content) {\n\t\t\t\ttagMapSet[tag] = true\n\t\t\t}\n\t\t}\n\t\ttagList := []string{}\n\t\tfor tag := range tagMapSet {\n\t\t\ttagList = append(tagList, tag)\n\t\t}\n\t\tsort.Strings(tagList)",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tagList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode tags response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/tag/:tagName\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\ttagName := c.Param(\"tagName\")\n\t\tif tagName == \"\" {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Tag name cannot be empty\")\n\t\t}",
"\t\ttagDelete := &api.TagDelete{\n\t\t\tName: tagName,\n\t\t\tCreatorID: userID,\n\t\t}\n\t\tif err := s.Store.DeleteTag(ctx, tagDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Tag name not found: %s\", tagName))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to delete tag name: %v\", tagName)).SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})\n}",
"var tagRegexp = regexp.MustCompile(`#([^\\s#]+)`)",
"func findTagListFromMemoContent(memoContent string) []string {\n\ttagMapSet := make(map[string]bool)\n\tmatches := tagRegexp.FindAllStringSubmatch(memoContent, -1)\n\tfor _, v := range matches {\n\t\ttagName := v[1]\n\t\ttagMapSet[tagName] = true\n\t}",
"\ttagList := []string{}\n\tfor tag := range tagMapSet {\n\t\ttagList = append(tagList, tag)\n\t}\n\tsort.Strings(tagList)\n\treturn tagList\n}"
] |
[
1,
1,
1,
1,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n)",
"func (s *Server) registerTagRoutes(g *echo.Group) {\n\tg.POST(\"/tag\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n",
"\t\ttagUpsert := &api.TagUpsert{}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(tagUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post tag request\").SetInternal(err)\n\t\t}\n\t\tif tagUpsert.Name == \"\" {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Tag name shouldn't be empty\")\n\t\t}\n",
"\t\ttagUpsert.CreatorID = userID",
"\t\ttag, err := s.Store.UpsertTag(ctx, tagUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert tag\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"tag created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tag.Name)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode tag response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/tag\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\ttagFind := &api.TagFind{}\n\t\tif userID, err := strconv.Atoi(c.QueryParam(\"creatorId\")); err == nil {\n\t\t\ttagFind.CreatorID = userID\n\t\t}",
"\t\tif tagFind.CreatorID == 0 {\n\t\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\t\tif !ok {\n\t\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user id to find tag\")\n\t\t\t}\n\t\t\ttagFind.CreatorID = currentUserID\n\t\t}",
"\t\ttagList, err := s.Store.FindTagList(ctx, tagFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find tag list\").SetInternal(err)\n\t\t}",
"\t\ttagNameList := []string{}\n\t\tfor _, tag := range tagList {\n\t\t\ttagNameList = append(tagNameList, tag.Name)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tagNameList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode tags response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/tag/suggestion\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()",
"\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Missing user session\")\n\t\t}",
"\t\tcontentSearch := \"#\"\n\t\tnormalRowStatus := api.Normal\n\t\tmemoFind := api.MemoFind{",
"\t\t\tCreatorID: &userID,",
"\t\t\tContentSearch: &contentSearch,\n\t\t\tRowStatus: &normalRowStatus,",
"",
"\t\t}",
"\t\tmemoList, err := s.Store.FindMemoList(ctx, &memoFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find memo list\").SetInternal(err)\n\t\t}",
"\t\ttagMapSet := make(map[string]bool)\n\t\tfor _, memo := range memoList {\n\t\t\tfor _, tag := range findTagListFromMemoContent(memo.Content) {\n\t\t\t\ttagMapSet[tag] = true\n\t\t\t}\n\t\t}\n\t\ttagList := []string{}\n\t\tfor tag := range tagMapSet {\n\t\t\ttagList = append(tagList, tag)\n\t\t}\n\t\tsort.Strings(tagList)",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tagList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode tags response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/tag/:tagName\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}",
"\t\ttagName := c.Param(\"tagName\")\n\t\tif tagName == \"\" {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Tag name cannot be empty\")\n\t\t}",
"\t\ttagDelete := &api.TagDelete{\n\t\t\tName: tagName,\n\t\t\tCreatorID: userID,\n\t\t}\n\t\tif err := s.Store.DeleteTag(ctx, tagDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"Tag name not found: %s\", tagName))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to delete tag name: %v\", tagName)).SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})\n}",
"var tagRegexp = regexp.MustCompile(`#([^\\s#]+)`)",
"func findTagListFromMemoContent(memoContent string) []string {\n\ttagMapSet := make(map[string]bool)\n\tmatches := tagRegexp.FindAllStringSubmatch(memoContent, -1)\n\tfor _, v := range matches {\n\t\ttagName := v[1]\n\t\ttagMapSet[tagName] = true\n\t}",
"\ttagList := []string{}\n\tfor tag := range tagMapSet {\n\t\ttagList = append(tagList, tag)\n\t}\n\tsort.Strings(tagList)\n\treturn tagList\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n\t\"golang.org/x/crypto/bcrypt\"\n)",
"func (s *Server) registerUserRoutes(g *echo.Group) {\n\tg.POST(\"/user\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing auth session\")\n\t\t}\n\t\tcurrentUser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user by id\").SetInternal(err)\n\t\t}\n\t\tif currentUser.Role != api.Host {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Only Host user can create member.\")\n\t\t}",
"\t\tuserCreate := &api.UserCreate{\n\t\t\tOpenID: common.GenUUID(),\n\t\t}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(userCreate); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post user request\").SetInternal(err)\n\t\t}",
"",
"\n\t\tif err := userCreate.Validate(); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user create format.\").SetInternal(err)",
"\t\t}",
"\t\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(userCreate.Password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to generate password hash\").SetInternal(err)\n\t\t}",
"\t\tuserCreate.PasswordHash = string(passwordHash)\n\t\tuser, err := s.Store.CreateUser(ctx, userCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create user\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/user\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserList, err := s.Store.FindUserList(ctx, &api.UserFind{})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch user list\").SetInternal(err)\n\t\t}",
"\t\tfor _, user := range userList {\n\t\t\t// data desensitize\n\t\t\tuser.OpenID = \"\"",
"",
"\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(userList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\t// GET /api/user/me is used to check if the user is logged in.\n\tg.GET(\"/user/me\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing auth session\")\n\t\t}",
"\t\tuserFind := &api.UserFind{\n\t\t\tID: &userID,\n\t\t}\n\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}",
"\t\tuserSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{\n\t\t\tUserID: userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find userSettingList\").SetInternal(err)\n\t\t}\n\t\tuser.UserSettingList = userSettingList",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/user/setting\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing auth session\")\n\t\t}",
"\t\tuserSettingUpsert := &api.UserSettingUpsert{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(userSettingUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post user setting upsert request\").SetInternal(err)\n\t\t}\n\t\tif err := userSettingUpsert.Validate(); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user setting format\").SetInternal(err)\n\t\t}",
"\t\tuserSettingUpsert.UserID = userID\n\t\tuserSetting, err := s.Store.UpsertUserSetting(ctx, userSettingUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert user setting\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(userSetting)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user setting response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/user/:id\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tid, err := strconv.Atoi(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted user id\").SetInternal(err)\n\t\t}",
"\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &id,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch user\").SetInternal(err)\n\t\t}",
"\t\tif user != nil {\n\t\t\t// data desensitize\n\t\t\tuser.OpenID = \"\"",
"",
"\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/user/:id\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, err := strconv.Atoi(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"id\"))).SetInternal(err)\n\t\t}\n\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tcurrentUser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: ¤tUserID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}\n\t\tif currentUser == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Current session user not found with ID: %d\", currentUserID)).SetInternal(err)\n\t\t} else if currentUser.Role != api.Host && currentUserID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"Access forbidden for current session user\").SetInternal(err)\n\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tuserPatch := &api.UserPatch{",
"\t\t\tID: userID,",
"\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(userPatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch user request\").SetInternal(err)\n\t\t}",
"",
"\t\tif err := userPatch.Validate(); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user patch format.\").SetInternal(err)",
"\t\t}",
"\t\tif userPatch.Password != nil && *userPatch.Password != \"\" {\n\t\t\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(*userPatch.Password), bcrypt.DefaultCost)\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to generate password hash\").SetInternal(err)\n\t\t\t}",
"\t\t\tpasswordHashStr := string(passwordHash)\n\t\t\tuserPatch.PasswordHash = &passwordHashStr\n\t\t}",
"\t\tif userPatch.ResetOpenID != nil && *userPatch.ResetOpenID {\n\t\t\topenID := common.GenUUID()\n\t\t\tuserPatch.OpenID = &openID\n\t\t}",
"\t\tuser, err := s.Store.PatchUser(ctx, userPatch)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch user\").SetInternal(err)\n\t\t}",
"\t\tuserSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{\n\t\t\tUserID: userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find userSettingList\").SetInternal(err)\n\t\t}\n\t\tuser.UserSettingList = userSettingList",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/user/:id\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tcurrentUser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: ¤tUserID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}\n\t\tif currentUser == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Current session user not found with ID: %d\", currentUserID)).SetInternal(err)\n\t\t} else if currentUser.Role != api.Host {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"Access forbidden for current session user\").SetInternal(err)\n\t\t}",
"\t\tuserID, err := strconv.Atoi(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"id\"))).SetInternal(err)\n\t\t}",
"\t\tuserDelete := &api.UserDelete{\n\t\t\tID: userID,\n\t\t}\n\t\tif err := s.Store.DeleteUser(ctx, userDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"User ID not found: %d\", userID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to delete user\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\n\t})\n}"
] |
[
1,
1,
1,
1,
1,
0,
0,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
0,
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"package server",
"import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"",
"\t\"github.com/usememos/memos/api\"\n\t\"github.com/usememos/memos/common\"\n\tmetric \"github.com/usememos/memos/plugin/metrics\"",
"\t\"github.com/labstack/echo/v4\"\n\t\"golang.org/x/crypto/bcrypt\"\n)",
"func (s *Server) registerUserRoutes(g *echo.Group) {\n\tg.POST(\"/user\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing auth session\")\n\t\t}\n\t\tcurrentUser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user by id\").SetInternal(err)\n\t\t}\n\t\tif currentUser.Role != api.Host {",
"\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Only Host user can create member\")\n\t\t}",
"\t\tuserCreate := &api.UserCreate{}",
"\t\tif err := json.NewDecoder(c.Request().Body).Decode(userCreate); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post user request\").SetInternal(err)\n\t\t}",
"\t\tif userCreate.Role == api.Host {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"Could not create host user\")\n\t\t}\n\t\tuserCreate.OpenID = common.GenUUID()",
"\n\t\tif err := userCreate.Validate(); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user create format\").SetInternal(err)",
"\t\t}",
"\t\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(userCreate.Password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to generate password hash\").SetInternal(err)\n\t\t}",
"\t\tuserCreate.PasswordHash = string(passwordHash)\n\t\tuser, err := s.Store.CreateUser(ctx, userCreate)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to create user\").SetInternal(err)\n\t\t}\n\t\ts.Collector.Collect(ctx, &metric.Metric{\n\t\t\tName: \"user created\",\n\t\t})",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/user\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserList, err := s.Store.FindUserList(ctx, &api.UserFind{})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch user list\").SetInternal(err)\n\t\t}",
"\t\tfor _, user := range userList {\n\t\t\t// data desensitize\n\t\t\tuser.OpenID = \"\"",
"\t\t\tuser.Email = \"\"",
"\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(userList)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user list response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\t// GET /api/user/me is used to check if the user is logged in.\n\tg.GET(\"/user/me\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing auth session\")\n\t\t}",
"\t\tuserFind := &api.UserFind{\n\t\t\tID: &userID,\n\t\t}\n\t\tuser, err := s.Store.FindUser(ctx, userFind)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}",
"\t\tuserSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{\n\t\t\tUserID: userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find userSettingList\").SetInternal(err)\n\t\t}\n\t\tuser.UserSettingList = userSettingList",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.POST(\"/user/setting\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing auth session\")\n\t\t}",
"\t\tuserSettingUpsert := &api.UserSettingUpsert{}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(userSettingUpsert); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted post user setting upsert request\").SetInternal(err)\n\t\t}\n\t\tif err := userSettingUpsert.Validate(); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user setting format\").SetInternal(err)\n\t\t}",
"\t\tuserSettingUpsert.UserID = userID\n\t\tuserSetting, err := s.Store.UpsertUserSetting(ctx, userSettingUpsert)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to upsert user setting\").SetInternal(err)\n\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(userSetting)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user setting response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.GET(\"/user/:id\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tid, err := strconv.Atoi(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted user id\").SetInternal(err)\n\t\t}",
"\t\tuser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: &id,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to fetch user\").SetInternal(err)\n\t\t}",
"\t\tif user != nil {\n\t\t\t// data desensitize\n\t\t\tuser.OpenID = \"\"",
"\t\t\tuser.Email = \"\"",
"\t\t}",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.PATCH(\"/user/:id\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tuserID, err := strconv.Atoi(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"id\"))).SetInternal(err)\n\t\t}\n\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tcurrentUser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: ¤tUserID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}\n\t\tif currentUser == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Current session user not found with ID: %d\", currentUserID)).SetInternal(err)\n\t\t} else if currentUser.Role != api.Host && currentUserID != userID {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"Access forbidden for current session user\").SetInternal(err)\n\t\t}",
"\t\tcurrentTs := time.Now().Unix()\n\t\tuserPatch := &api.UserPatch{",
"",
"\t\t\tUpdatedTs: ¤tTs,\n\t\t}\n\t\tif err := json.NewDecoder(c.Request().Body).Decode(userPatch); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Malformatted patch user request\").SetInternal(err)\n\t\t}",
"\t\tuserPatch.ID = userID",
"\t\tif err := userPatch.Validate(); err != nil {",
"\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid user patch format\").SetInternal(err)",
"\t\t}",
"\t\tif userPatch.Password != nil && *userPatch.Password != \"\" {\n\t\t\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(*userPatch.Password), bcrypt.DefaultCost)\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to generate password hash\").SetInternal(err)\n\t\t\t}",
"\t\t\tpasswordHashStr := string(passwordHash)\n\t\t\tuserPatch.PasswordHash = &passwordHashStr\n\t\t}",
"\t\tif userPatch.ResetOpenID != nil && *userPatch.ResetOpenID {\n\t\t\topenID := common.GenUUID()\n\t\t\tuserPatch.OpenID = &openID\n\t\t}",
"\t\tuser, err := s.Store.PatchUser(ctx, userPatch)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to patch user\").SetInternal(err)\n\t\t}",
"\t\tuserSettingList, err := s.Store.FindUserSettingList(ctx, &api.UserSettingFind{\n\t\t\tUserID: userID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find userSettingList\").SetInternal(err)\n\t\t}\n\t\tuser.UserSettingList = userSettingList",
"\t\tc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)\n\t\tif err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(user)); err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to encode user response\").SetInternal(err)\n\t\t}\n\t\treturn nil\n\t})",
"\tg.DELETE(\"/user/:id\", func(c echo.Context) error {\n\t\tctx := c.Request().Context()\n\t\tcurrentUserID, ok := c.Get(getUserIDContextKey()).(int)\n\t\tif !ok {\n\t\t\treturn echo.NewHTTPError(http.StatusUnauthorized, \"Missing user in session\")\n\t\t}\n\t\tcurrentUser, err := s.Store.FindUser(ctx, &api.UserFind{\n\t\t\tID: ¤tUserID,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to find user\").SetInternal(err)\n\t\t}\n\t\tif currentUser == nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Current session user not found with ID: %d\", currentUserID)).SetInternal(err)\n\t\t} else if currentUser.Role != api.Host {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"Access forbidden for current session user\").SetInternal(err)\n\t\t}",
"\t\tuserID, err := strconv.Atoi(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"ID is not a number: %s\", c.Param(\"id\"))).SetInternal(err)\n\t\t}",
"\t\tuserDelete := &api.UserDelete{\n\t\t\tID: userID,\n\t\t}\n\t\tif err := s.Store.DeleteUser(ctx, userDelete); err != nil {\n\t\t\tif common.ErrorCode(err) == common.NotFound {\n\t\t\t\treturn echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf(\"User ID not found: %d\", userID))\n\t\t\t}\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to delete user\").SetInternal(err)\n\t\t}",
"\t\treturn c.JSON(http.StatusOK, true)\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [81, 21, 12, 24, 20, 11, 54, 118, 545, 229, 127, 131, 108, 203], "buggy_code_start_loc": [49, 11, 11, 23, 19, 10, 53, 87, 27, 58, 24, 79, 26, 32], "filenames": ["api/memo.go", "api/memo_organizer.go", "api/memo_resource.go", "api/resource.go", "api/shortcut.go", "api/tag.go", "api/user_setting.go", "server/auth.go", "server/memo.go", "server/resource.go", "server/shortcut.go", "server/system.go", "server/tag.go", "server/user.go"], "fixing_code_end_loc": [81, 20, 12, 24, 20, 11, 54, 118, 559, 232, 152, 140, 93, 207], "fixing_code_start_loc": [49, 12, 11, 23, 19, 10, 53, 87, 27, 59, 24, 79, 26, 32], "message": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:usememos:memos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E75ADB4-9898-49F3-BF80-3C54F4CE0FB4", "versionEndExcluding": "0.9.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Improper Handling of Insufficient Permissions or Privileges in GitHub repository usememos/memos prior to 0.9.1."}], "evaluatorComment": null, "id": "CVE-2022-4863", "lastModified": "2023-01-10T15:19:48.147", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 8.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 5.9, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:N/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T16:15:09.347", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/42751929-e511-49a9-888d-d5b610da2a45"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-280"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/usememos/memos/commit/3556ae4e651d9443dc3bb8a170dd3cc726517a53"}, "type": "CWE-280"}
| 305
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import asyncio\nfrom typing import Dict, Optional, Tuple",
"from mitmproxy import command, ctx, exceptions, flow, http, log, master, options, platform, tcp, websocket\nfrom mitmproxy.flow import Flow\nfrom mitmproxy.proxy import commands, events, server_hooks\nfrom mitmproxy.proxy import server\nfrom mitmproxy.proxy.layers.tcp import TcpMessageInjected\nfrom mitmproxy.proxy.layers.websocket import WebSocketMessageInjected\nfrom mitmproxy.utils import asyncio_utils, human\nfrom wsproto.frame_protocol import Opcode",
"\nclass ProxyConnectionHandler(server.StreamConnectionHandler):\n master: master.Master",
" def __init__(self, master, r, w, options):\n self.master = master\n super().__init__(r, w, options)\n self.log_prefix = f\"{human.format_address(self.client.peername)}: \"",
" async def handle_hook(self, hook: commands.StartHook) -> None:\n with self.timeout_watchdog.disarm():\n # We currently only support single-argument hooks.\n data, = hook.args()\n await self.master.addons.handle_lifecycle(hook)\n if isinstance(data, flow.Flow):\n await data.wait_for_resume()",
" def log(self, message: str, level: str = \"info\") -> None:\n x = log.LogEntry(self.log_prefix + message, level)\n asyncio_utils.create_task(\n self.master.addons.handle_lifecycle(log.AddLogHook(x)),\n name=\"ProxyConnectionHandler.log\"\n )",
"\nclass Proxyserver:\n \"\"\"\n This addon runs the actual proxy server.\n \"\"\"\n server: Optional[asyncio.AbstractServer]\n listen_port: int\n master: master.Master\n options: options.Options\n is_running: bool\n _connections: Dict[Tuple, ProxyConnectionHandler]",
" def __init__(self):\n self._lock = asyncio.Lock()\n self.server = None\n self.is_running = False\n self._connections = {}",
" def __repr__(self):\n return f\"ProxyServer({'running' if self.server else 'stopped'}, {len(self._connections)} active conns)\"",
" def load(self, loader):\n loader.add_option(\n \"connection_strategy\", str, \"eager\",\n \"Determine when server connections should be established. When set to lazy, mitmproxy \"\n \"tries to defer establishing an upstream connection as long as possible. This makes it possible to \"\n \"use server replay while being offline. When set to eager, mitmproxy can detect protocols with \"\n \"server-side greetings, as well as accurately mirror TLS ALPN negotiation.\",\n choices=(\"eager\", \"lazy\")\n )\n loader.add_option(\n \"stream_large_bodies\", Optional[str], None,\n \"\"\"\n Stream data to the client if response body exceeds the given\n threshold. If streamed, the body will not be stored in any way.\n Understands k/m/g suffixes, i.e. 3m for 3 megabytes.\n \"\"\"\n )\n loader.add_option(\n \"body_size_limit\", Optional[str], None,\n \"\"\"\n Byte size limit of HTTP request and response bodies. Understands\n k/m/g suffixes, i.e. 3m for 3 megabytes.\n \"\"\"\n )\n loader.add_option(\n \"keep_host_header\", bool, False,\n \"\"\"\n Reverse Proxy: Keep the original host header instead of rewriting it\n to the reverse proxy target.\n \"\"\"\n )\n loader.add_option(\n \"proxy_debug\", bool, False,\n \"Enable debug logs in the proxy core.\",\n )\n loader.add_option(\n \"normalize_outbound_headers\", bool, True,\n \"\"\"\n Normalize outgoing HTTP/2 header names, but emit a warning when doing so.\n HTTP/2 does not allow uppercase header names. This option makes sure that HTTP/2 headers set\n in custom scripts are lowercased before they are sent.",
"",
" \"\"\",\n )",
" async def running(self):\n self.master = ctx.master\n self.options = ctx.options\n self.is_running = True\n await self.refresh_server()",
" def configure(self, updated):\n if \"stream_large_bodies\" in updated:\n try:\n human.parse_size(ctx.options.stream_large_bodies)\n except ValueError:\n raise exceptions.OptionsError(f\"Invalid stream_large_bodies specification: \"\n f\"{ctx.options.stream_large_bodies}\")\n if \"body_size_limit\" in updated:\n try:\n human.parse_size(ctx.options.body_size_limit)\n except ValueError:\n raise exceptions.OptionsError(f\"Invalid body_size_limit specification: \"\n f\"{ctx.options.body_size_limit}\")\n if \"mode\" in updated and ctx.options.mode == \"transparent\": # pragma: no cover\n platform.init_transparent_mode()\n if self.is_running and any(x in updated for x in [\"server\", \"listen_host\", \"listen_port\"]):\n asyncio.create_task(self.refresh_server())",
" async def refresh_server(self):\n async with self._lock:\n if self.server:\n await self.shutdown_server()\n self.server = None\n if ctx.options.server:\n if not ctx.master.addons.get(\"nextlayer\"):\n ctx.log.warn(\"Warning: Running proxyserver without nextlayer addon!\")\n try:\n self.server = await asyncio.start_server(\n self.handle_connection,\n self.options.listen_host,\n self.options.listen_port,\n )\n except OSError as e:\n ctx.log.error(str(e))\n return\n # TODO: This is a bit confusing currently for `-p 0`.\n addrs = {f\"http://{human.format_address(s.getsockname())}\" for s in self.server.sockets}\n ctx.log.info(f\"Proxy server listening at {' and '.join(addrs)}\")",
" async def shutdown_server(self):\n ctx.log.info(\"Stopping server...\")\n self.server.close()\n await self.server.wait_closed()\n self.server = None",
" async def handle_connection(self, r, w):\n peername = w.get_extra_info('peername')\n asyncio_utils.set_task_debug_info(\n asyncio.current_task(),\n name=f\"Proxyserver.handle_connection\",\n client=peername,\n )\n handler = ProxyConnectionHandler(\n self.master,\n r,\n w,\n self.options\n )\n self._connections[peername] = handler\n try:\n await handler.handle_client()\n finally:\n del self._connections[peername]",
" def inject_event(self, event: events.MessageInjected):\n if event.flow.client_conn.peername not in self._connections:\n raise ValueError(\"Flow is not from a live connection.\")\n self._connections[event.flow.client_conn.peername].server_event(event)",
" @command.command(\"inject.websocket\")\n def inject_websocket(self, flow: Flow, to_client: bool, message: bytes, is_text: bool = True):\n if not isinstance(flow, http.HTTPFlow) or not flow.websocket:\n ctx.log.warn(\"Cannot inject WebSocket messages into non-WebSocket flows.\")",
" msg = websocket.WebSocketMessage(\n Opcode.TEXT if is_text else Opcode.BINARY,\n not to_client,\n message\n )\n event = WebSocketMessageInjected(flow, msg)\n try:\n self.inject_event(event)\n except ValueError as e:\n ctx.log.warn(str(e))",
" @command.command(\"inject.tcp\")\n def inject_tcp(self, flow: Flow, to_client: bool, message: bytes):\n if not isinstance(flow, tcp.TCPFlow):\n ctx.log.warn(\"Cannot inject TCP messages into non-TCP flows.\")",
" event = TcpMessageInjected(flow, tcp.TCPMessage(not to_client, message))\n try:\n self.inject_event(event)\n except ValueError as e:\n ctx.log.warn(str(e))",
" def server_connect(self, ctx: server_hooks.ServerConnectionHookData):\n assert ctx.server.address\n self_connect = (\n ctx.server.address[1] == self.options.listen_port\n and\n ctx.server.address[0] in (\"localhost\", \"127.0.0.1\", \"::1\", self.options.listen_host)\n )\n if self_connect:\n ctx.server.error = (\n \"Request destination unknown. \"\n \"Unable to figure out where this request should be forwarded to.\"\n )"
] |
[
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import asyncio\nfrom typing import Dict, Optional, Tuple",
"from mitmproxy import command, ctx, exceptions, flow, http, log, master, options, platform, tcp, websocket\nfrom mitmproxy.flow import Flow\nfrom mitmproxy.proxy import commands, events, server_hooks\nfrom mitmproxy.proxy import server\nfrom mitmproxy.proxy.layers.tcp import TcpMessageInjected\nfrom mitmproxy.proxy.layers.websocket import WebSocketMessageInjected\nfrom mitmproxy.utils import asyncio_utils, human\nfrom wsproto.frame_protocol import Opcode",
"\nclass ProxyConnectionHandler(server.StreamConnectionHandler):\n master: master.Master",
" def __init__(self, master, r, w, options):\n self.master = master\n super().__init__(r, w, options)\n self.log_prefix = f\"{human.format_address(self.client.peername)}: \"",
" async def handle_hook(self, hook: commands.StartHook) -> None:\n with self.timeout_watchdog.disarm():\n # We currently only support single-argument hooks.\n data, = hook.args()\n await self.master.addons.handle_lifecycle(hook)\n if isinstance(data, flow.Flow):\n await data.wait_for_resume()",
" def log(self, message: str, level: str = \"info\") -> None:\n x = log.LogEntry(self.log_prefix + message, level)\n asyncio_utils.create_task(\n self.master.addons.handle_lifecycle(log.AddLogHook(x)),\n name=\"ProxyConnectionHandler.log\"\n )",
"\nclass Proxyserver:\n \"\"\"\n This addon runs the actual proxy server.\n \"\"\"\n server: Optional[asyncio.AbstractServer]\n listen_port: int\n master: master.Master\n options: options.Options\n is_running: bool\n _connections: Dict[Tuple, ProxyConnectionHandler]",
" def __init__(self):\n self._lock = asyncio.Lock()\n self.server = None\n self.is_running = False\n self._connections = {}",
" def __repr__(self):\n return f\"ProxyServer({'running' if self.server else 'stopped'}, {len(self._connections)} active conns)\"",
" def load(self, loader):\n loader.add_option(\n \"connection_strategy\", str, \"eager\",\n \"Determine when server connections should be established. When set to lazy, mitmproxy \"\n \"tries to defer establishing an upstream connection as long as possible. This makes it possible to \"\n \"use server replay while being offline. When set to eager, mitmproxy can detect protocols with \"\n \"server-side greetings, as well as accurately mirror TLS ALPN negotiation.\",\n choices=(\"eager\", \"lazy\")\n )\n loader.add_option(\n \"stream_large_bodies\", Optional[str], None,\n \"\"\"\n Stream data to the client if response body exceeds the given\n threshold. If streamed, the body will not be stored in any way.\n Understands k/m/g suffixes, i.e. 3m for 3 megabytes.\n \"\"\"\n )\n loader.add_option(\n \"body_size_limit\", Optional[str], None,\n \"\"\"\n Byte size limit of HTTP request and response bodies. Understands\n k/m/g suffixes, i.e. 3m for 3 megabytes.\n \"\"\"\n )\n loader.add_option(\n \"keep_host_header\", bool, False,\n \"\"\"\n Reverse Proxy: Keep the original host header instead of rewriting it\n to the reverse proxy target.\n \"\"\"\n )\n loader.add_option(\n \"proxy_debug\", bool, False,\n \"Enable debug logs in the proxy core.\",\n )\n loader.add_option(\n \"normalize_outbound_headers\", bool, True,\n \"\"\"\n Normalize outgoing HTTP/2 header names, but emit a warning when doing so.\n HTTP/2 does not allow uppercase header names. This option makes sure that HTTP/2 headers set\n in custom scripts are lowercased before they are sent.",
" \"\"\",\n )\n loader.add_option(\n \"validate_inbound_headers\", bool, True,\n \"\"\"\n Make sure that incoming HTTP requests are not malformed.\n Disabling this option makes mitmproxy vulnerable to HTTP smuggling attacks.",
" \"\"\",\n )",
" async def running(self):\n self.master = ctx.master\n self.options = ctx.options\n self.is_running = True\n await self.refresh_server()",
" def configure(self, updated):\n if \"stream_large_bodies\" in updated:\n try:\n human.parse_size(ctx.options.stream_large_bodies)\n except ValueError:\n raise exceptions.OptionsError(f\"Invalid stream_large_bodies specification: \"\n f\"{ctx.options.stream_large_bodies}\")\n if \"body_size_limit\" in updated:\n try:\n human.parse_size(ctx.options.body_size_limit)\n except ValueError:\n raise exceptions.OptionsError(f\"Invalid body_size_limit specification: \"\n f\"{ctx.options.body_size_limit}\")\n if \"mode\" in updated and ctx.options.mode == \"transparent\": # pragma: no cover\n platform.init_transparent_mode()\n if self.is_running and any(x in updated for x in [\"server\", \"listen_host\", \"listen_port\"]):\n asyncio.create_task(self.refresh_server())",
" async def refresh_server(self):\n async with self._lock:\n if self.server:\n await self.shutdown_server()\n self.server = None\n if ctx.options.server:\n if not ctx.master.addons.get(\"nextlayer\"):\n ctx.log.warn(\"Warning: Running proxyserver without nextlayer addon!\")\n try:\n self.server = await asyncio.start_server(\n self.handle_connection,\n self.options.listen_host,\n self.options.listen_port,\n )\n except OSError as e:\n ctx.log.error(str(e))\n return\n # TODO: This is a bit confusing currently for `-p 0`.\n addrs = {f\"http://{human.format_address(s.getsockname())}\" for s in self.server.sockets}\n ctx.log.info(f\"Proxy server listening at {' and '.join(addrs)}\")",
" async def shutdown_server(self):\n ctx.log.info(\"Stopping server...\")\n self.server.close()\n await self.server.wait_closed()\n self.server = None",
" async def handle_connection(self, r, w):\n peername = w.get_extra_info('peername')\n asyncio_utils.set_task_debug_info(\n asyncio.current_task(),\n name=f\"Proxyserver.handle_connection\",\n client=peername,\n )\n handler = ProxyConnectionHandler(\n self.master,\n r,\n w,\n self.options\n )\n self._connections[peername] = handler\n try:\n await handler.handle_client()\n finally:\n del self._connections[peername]",
" def inject_event(self, event: events.MessageInjected):\n if event.flow.client_conn.peername not in self._connections:\n raise ValueError(\"Flow is not from a live connection.\")\n self._connections[event.flow.client_conn.peername].server_event(event)",
" @command.command(\"inject.websocket\")\n def inject_websocket(self, flow: Flow, to_client: bool, message: bytes, is_text: bool = True):\n if not isinstance(flow, http.HTTPFlow) or not flow.websocket:\n ctx.log.warn(\"Cannot inject WebSocket messages into non-WebSocket flows.\")",
" msg = websocket.WebSocketMessage(\n Opcode.TEXT if is_text else Opcode.BINARY,\n not to_client,\n message\n )\n event = WebSocketMessageInjected(flow, msg)\n try:\n self.inject_event(event)\n except ValueError as e:\n ctx.log.warn(str(e))",
" @command.command(\"inject.tcp\")\n def inject_tcp(self, flow: Flow, to_client: bool, message: bytes):\n if not isinstance(flow, tcp.TCPFlow):\n ctx.log.warn(\"Cannot inject TCP messages into non-TCP flows.\")",
" event = TcpMessageInjected(flow, tcp.TCPMessage(not to_client, message))\n try:\n self.inject_event(event)\n except ValueError as e:\n ctx.log.warn(str(e))",
" def server_connect(self, ctx: server_hooks.ServerConnectionHookData):\n assert ctx.server.address\n self_connect = (\n ctx.server.address[1] == self.options.listen_port\n and\n ctx.server.address[0] in (\"localhost\", \"127.0.0.1\", \"::1\", self.options.listen_host)\n )\n if self_connect:\n ctx.server.error = (\n \"Request destination unknown. \"\n \"Unable to figure out where this request should be forwarded to.\"\n )"
] |
[
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"from .read import (\n read_request_head,\n read_response_head,\n connection_close,\n expected_http_body_size,",
"",
")\nfrom .assemble import (\n assemble_request, assemble_request_head,\n assemble_response, assemble_response_head,\n assemble_body,\n)",
"\n__all__ = [\n \"read_request_head\",\n \"read_response_head\",\n \"connection_close\",\n \"expected_http_body_size\",",
"",
" \"assemble_request\", \"assemble_request_head\",\n \"assemble_response\", \"assemble_response_head\",\n \"assemble_body\",\n]"
] |
[
1,
0,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"from .read import (\n read_request_head,\n read_response_head,\n connection_close,\n expected_http_body_size,",
" validate_headers,",
")\nfrom .assemble import (\n assemble_request, assemble_request_head,\n assemble_response, assemble_response_head,\n assemble_body,\n)",
"\n__all__ = [\n \"read_request_head\",\n \"read_response_head\",\n \"connection_close\",\n \"expected_http_body_size\",",
" \"validate_headers\",",
" \"assemble_request\", \"assemble_request_head\",\n \"assemble_response\", \"assemble_response_head\",\n \"assemble_body\",\n]"
] |
[
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import re\nimport time\nfrom typing import List, Tuple, Iterable, Optional",
"from mitmproxy.http import Request, Headers, Response\nfrom mitmproxy.net.http import url",
"\ndef get_header_tokens(headers, key):\n \"\"\"\n Retrieve all tokens for a header key. A number of different headers\n follow a pattern where each header line can containe comma-separated\n tokens, and headers can be set multiple times.\n \"\"\"\n if key not in headers:\n return []\n tokens = headers[key].split(\",\")\n return [token.strip() for token in tokens]",
"\ndef connection_close(http_version, headers):\n \"\"\"\n Checks the message to see if the client connection should be closed\n according to RFC 2616 Section 8.1.\n If we don't have a Connection header, HTTP 1.1 connections are assumed\n to be persistent.\n \"\"\"\n if \"connection\" in headers:\n tokens = get_header_tokens(headers, \"connection\")\n if \"close\" in tokens:\n return True\n elif \"keep-alive\" in tokens:\n return False",
" return http_version not in (\n \"HTTP/1.1\", b\"HTTP/1.1\",\n \"HTTP/2.0\", b\"HTTP/2.0\",\n )",
"",
"",
"def expected_http_body_size(\n request: Request,\n response: Optional[Response] = None\n) -> Optional[int]:\n \"\"\"\n Returns:\n The expected body length:\n - a positive integer, if the size is known in advance\n - None, if the size in unknown in advance (chunked encoding)\n - -1, if all data should be read until end of stream.",
" Raises:\n ValueError, if the content length header is invalid\n \"\"\"\n # Determine response size according to http://tools.ietf.org/html/rfc7230#section-3.3, which is inlined below.\n if not response:\n headers = request.headers\n else:\n headers = response.headers",
" # 1. Any response to a HEAD request and any response with a 1xx\n # (Informational), 204 (No Content), or 304 (Not Modified) status\n # code is always terminated by the first empty line after the\n # header fields, regardless of the header fields present in the\n # message, and thus cannot contain a message body.\n if request.method.upper() == \"HEAD\":\n return 0\n if 100 <= response.status_code <= 199:\n return 0\n if response.status_code in (204, 304):\n return 0",
" # 2. Any 2xx (Successful) response to a CONNECT request implies that\n # the connection will become a tunnel immediately after the empty\n # line that concludes the header fields. A client MUST ignore any\n # Content-Length or Transfer-Encoding header fields received in\n # such a message.\n if 200 <= response.status_code <= 299 and request.method.upper() == \"CONNECT\":\n return 0",
" # 3. If a Transfer-Encoding header field is present and the chunked\n # transfer coding (Section 4.1) is the final encoding, the message\n # body length is determined by reading and decoding the chunked\n # data until the transfer coding indicates the data is complete.\n #\n # If a Transfer-Encoding header field is present in a response and\n # the chunked transfer coding is not the final encoding, the\n # message body length is determined by reading the connection until\n # it is closed by the server. If a Transfer-Encoding header field\n # is present in a request and the chunked transfer coding is not\n # the final encoding, the message body length cannot be determined\n # reliably; the server MUST respond with the 400 (Bad Request)\n # status code and then close the connection.\n #\n # If a message is received with both a Transfer-Encoding and a\n # Content-Length header field, the Transfer-Encoding overrides the\n # Content-Length. Such a message might indicate an attempt to\n # perform request smuggling (Section 9.5) or response splitting\n # (Section 9.4) and ought to be handled as an error. A sender MUST\n # remove the received Content-Length field prior to forwarding such\n # a message downstream.\n #\n if \"transfer-encoding\" in headers:",
" if \"content-length\" in headers:\n raise ValueError(\"Received both a Transfer-Encoding and a Content-Length header, \"\n \"refusing as recommended in RFC 7230 Section 3.3.3. \"\n \"See https://github.com/mitmproxy/mitmproxy/issues/4799 for details.\")",
"\n te: str = headers[\"transfer-encoding\"]\n if not te.isascii():\n # guard against .lower() transforming non-ascii to ascii\n raise ValueError(f\"Invalid transfer encoding: {te!r}\")\n te = te.lower().strip(\"\\t \")\n te = re.sub(r\"[\\t ]*,[\\t ]*\", \",\", te)\n if te in (\n \"chunked\",\n \"compress,chunked\",\n \"deflate,chunked\",\n \"gzip,chunked\",\n ):\n return None\n elif te in (\n \"compress\",\n \"deflate\",\n \"gzip\",\n \"identity\",\n ):\n if response:\n return -1\n else:\n raise ValueError(f\"Invalid request transfer encoding, message body cannot be determined reliably.\")\n else:\n raise ValueError(f\"Unknown transfer encoding: {headers['transfer-encoding']!r}\")",
" # 4. If a message is received without Transfer-Encoding and with\n # either multiple Content-Length header fields having differing\n # field-values or a single Content-Length header field having an\n # invalid value, then the message framing is invalid and the\n # recipient MUST treat it as an unrecoverable error. If this is a\n # request message, the server MUST respond with a 400 (Bad Request)\n # status code and then close the connection. If this is a response\n # message received by a proxy, the proxy MUST close the connection\n # to the server, discard the received response, and send a 502 (Bad\n # Gateway) response to the client. If this is a response message\n # received by a user agent, the user agent MUST close the\n # connection to the server and discard the received response.\n #\n # 5. If a valid Content-Length header field is present without\n # Transfer-Encoding, its decimal value defines the expected message\n # body length in octets. If the sender closes the connection or\n # the recipient times out before the indicated number of octets are\n # received, the recipient MUST consider the message to be\n # incomplete and close the connection.\n if \"content-length\" in headers:\n sizes = headers.get_all(\"content-length\")\n different_content_length_headers = any(x != sizes[0] for x in sizes)\n if different_content_length_headers:\n raise ValueError(f\"Conflicting Content-Length headers: {sizes!r}\")\n try:\n size = int(sizes[0])\n except ValueError:\n raise ValueError(f\"Invalid Content-Length header: {sizes[0]!r}\")\n if size < 0:\n raise ValueError(f\"Negative Content-Length header: {sizes[0]!r}\")\n return size",
" # 6. If this is a request message and none of the above are true, then\n # the message body length is zero (no message body is present).\n if not response:\n return 0",
" # 7. Otherwise, this is a response message without a declared message\n # body length, so the message body length is determined by the\n # number of octets received prior to the server closing the\n # connection.\n return -1",
"\ndef raise_if_http_version_unknown(http_version: bytes) -> None:\n if not re.match(br\"^HTTP/\\d\\.\\d$\", http_version):\n raise ValueError(f\"Unknown HTTP version: {http_version!r}\")",
"\ndef _read_request_line(line: bytes) -> Tuple[str, int, bytes, bytes, bytes, bytes, bytes]:\n try:\n method, target, http_version = line.split()\n port: Optional[int]",
" if target == b\"*\" or target.startswith(b\"/\"):\n scheme, authority, path = b\"\", b\"\", target\n host, port = \"\", 0\n elif method == b\"CONNECT\":\n scheme, authority, path = b\"\", target, b\"\"\n host, port = url.parse_authority(authority, check=True)\n if not port:\n raise ValueError\n else:\n scheme, rest = target.split(b\"://\", maxsplit=1)\n authority, _, path_ = rest.partition(b\"/\")\n path = b\"/\" + path_\n host, port = url.parse_authority(authority, check=True)\n port = port or url.default_port(scheme)\n if not port:\n raise ValueError\n # TODO: we can probably get rid of this check?\n url.parse(target)",
" raise_if_http_version_unknown(http_version)\n except ValueError as e:\n raise ValueError(f\"Bad HTTP request line: {line!r}\") from e",
" return host, port, method, scheme, authority, path, http_version",
"\ndef _read_response_line(line: bytes) -> Tuple[bytes, int, bytes]:\n try:\n parts = line.split(None, 2)\n if len(parts) == 2: # handle missing message gracefully\n parts.append(b\"\")",
" http_version, status_code_str, reason = parts\n status_code = int(status_code_str)\n raise_if_http_version_unknown(http_version)\n except ValueError as e:\n raise ValueError(f\"Bad HTTP response line: {line!r}\") from e",
" return http_version, status_code, reason",
"\ndef _read_headers(lines: Iterable[bytes]) -> Headers:\n \"\"\"\n Read a set of headers.\n Stop once a blank line is reached.",
" Returns:\n A headers object",
" Raises:\n exceptions.HttpSyntaxException\n \"\"\"\n ret: List[Tuple[bytes, bytes]] = []\n for line in lines:\n if line[0] in b\" \\t\":\n if not ret:\n raise ValueError(\"Invalid headers\")\n # continued header\n ret[-1] = (ret[-1][0], ret[-1][1] + b'\\r\\n ' + line.strip())\n else:\n try:\n name, value = line.split(b\":\", 1)\n value = value.strip()\n if not name:\n raise ValueError()\n ret.append((name, value))\n except ValueError:\n raise ValueError(f\"Invalid header line: {line!r}\")\n return Headers(ret)",
"\ndef read_request_head(lines: List[bytes]) -> Request:\n \"\"\"\n Parse an HTTP request head (request line + headers) from an iterable of lines",
" Args:\n lines: The input lines",
" Returns:\n The HTTP request object (without body)",
" Raises:\n ValueError: The input is malformed.\n \"\"\"\n host, port, method, scheme, authority, path, http_version = _read_request_line(lines[0])\n headers = _read_headers(lines[1:])",
" return Request(\n host=host,\n port=port,\n method=method,\n scheme=scheme,\n authority=authority,\n path=path,\n http_version=http_version,\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None\n )",
"\ndef read_response_head(lines: List[bytes]) -> Response:\n \"\"\"\n Parse an HTTP response head (response line + headers) from an iterable of lines",
" Args:\n lines: The input lines",
" Returns:\n The HTTP response object (without body)",
" Raises:\n ValueError: The input is malformed.\n \"\"\"\n http_version, status_code, reason = _read_response_line(lines[0])\n headers = _read_headers(lines[1:])",
" return Response(\n http_version=http_version,\n status_code=status_code,\n reason=reason,\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None,\n )"
] |
[
1,
1,
1,
1,
1,
0,
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import re\nimport time\nfrom typing import List, Tuple, Iterable, Optional",
"from mitmproxy.http import Request, Headers, Response\nfrom mitmproxy.net.http import url",
"\ndef get_header_tokens(headers, key):\n \"\"\"\n Retrieve all tokens for a header key. A number of different headers\n follow a pattern where each header line can containe comma-separated\n tokens, and headers can be set multiple times.\n \"\"\"\n if key not in headers:\n return []\n tokens = headers[key].split(\",\")\n return [token.strip() for token in tokens]",
"\ndef connection_close(http_version, headers):\n \"\"\"\n Checks the message to see if the client connection should be closed\n according to RFC 2616 Section 8.1.\n If we don't have a Connection header, HTTP 1.1 connections are assumed\n to be persistent.\n \"\"\"\n if \"connection\" in headers:\n tokens = get_header_tokens(headers, \"connection\")\n if \"close\" in tokens:\n return True\n elif \"keep-alive\" in tokens:\n return False",
" return http_version not in (\n \"HTTP/1.1\", b\"HTTP/1.1\",\n \"HTTP/2.0\", b\"HTTP/2.0\",\n )",
"",
"# https://datatracker.ietf.org/doc/html/rfc7230#section-3.2: Header fields are tokens.\n# \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\" / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\" / DIGIT / ALPHA\n_valid_header_name = re.compile(rb\"^[!#$%&'*+\\-.^_`|~0-9a-zA-Z]+$\")",
"\ndef validate_headers(\n headers: Headers\n) -> None:\n \"\"\"\n Validate headers to avoid request smuggling attacks. Raises a ValueError if they are malformed.\n \"\"\"",
" te_found = False\n cl_found = False",
" for (name, value) in headers.fields:\n if not _valid_header_name.match(name):\n raise ValueError(f\"Received an invalid header name: {name!r}. Invalid header names may introduce \"\n f\"request smuggling vulnerabilities. Disable the validate_inbound_headers option \"\n f\"to skip this security check.\")",
" name_lower = name.lower()\n te_found = te_found or name_lower == b\"transfer-encoding\"\n cl_found = cl_found or name_lower == b\"content-length\"",
" if te_found and cl_found:\n raise ValueError(\"Received both a Transfer-Encoding and a Content-Length header, \"\n \"refusing as recommended in RFC 7230 Section 3.3.3. \"\n \"See https://github.com/mitmproxy/mitmproxy/issues/4799 for details. \"\n \"Disable the validate_inbound_headers option to skip this security check.\")",
"",
"def expected_http_body_size(\n request: Request,\n response: Optional[Response] = None\n) -> Optional[int]:\n \"\"\"\n Returns:\n The expected body length:\n - a positive integer, if the size is known in advance\n - None, if the size in unknown in advance (chunked encoding)\n - -1, if all data should be read until end of stream.",
" Raises:\n ValueError, if the content length header is invalid\n \"\"\"\n # Determine response size according to http://tools.ietf.org/html/rfc7230#section-3.3, which is inlined below.\n if not response:\n headers = request.headers\n else:\n headers = response.headers",
" # 1. Any response to a HEAD request and any response with a 1xx\n # (Informational), 204 (No Content), or 304 (Not Modified) status\n # code is always terminated by the first empty line after the\n # header fields, regardless of the header fields present in the\n # message, and thus cannot contain a message body.\n if request.method.upper() == \"HEAD\":\n return 0\n if 100 <= response.status_code <= 199:\n return 0\n if response.status_code in (204, 304):\n return 0",
" # 2. Any 2xx (Successful) response to a CONNECT request implies that\n # the connection will become a tunnel immediately after the empty\n # line that concludes the header fields. A client MUST ignore any\n # Content-Length or Transfer-Encoding header fields received in\n # such a message.\n if 200 <= response.status_code <= 299 and request.method.upper() == \"CONNECT\":\n return 0",
" # 3. If a Transfer-Encoding header field is present and the chunked\n # transfer coding (Section 4.1) is the final encoding, the message\n # body length is determined by reading and decoding the chunked\n # data until the transfer coding indicates the data is complete.\n #\n # If a Transfer-Encoding header field is present in a response and\n # the chunked transfer coding is not the final encoding, the\n # message body length is determined by reading the connection until\n # it is closed by the server. If a Transfer-Encoding header field\n # is present in a request and the chunked transfer coding is not\n # the final encoding, the message body length cannot be determined\n # reliably; the server MUST respond with the 400 (Bad Request)\n # status code and then close the connection.\n #\n # If a message is received with both a Transfer-Encoding and a\n # Content-Length header field, the Transfer-Encoding overrides the\n # Content-Length. Such a message might indicate an attempt to\n # perform request smuggling (Section 9.5) or response splitting\n # (Section 9.4) and ought to be handled as an error. A sender MUST\n # remove the received Content-Length field prior to forwarding such\n # a message downstream.\n #\n if \"transfer-encoding\" in headers:",
" # we should make sure that there isn't also a content-length header.\n # this is already handled in validate_headers.",
"\n te: str = headers[\"transfer-encoding\"]\n if not te.isascii():\n # guard against .lower() transforming non-ascii to ascii\n raise ValueError(f\"Invalid transfer encoding: {te!r}\")\n te = te.lower().strip(\"\\t \")\n te = re.sub(r\"[\\t ]*,[\\t ]*\", \",\", te)\n if te in (\n \"chunked\",\n \"compress,chunked\",\n \"deflate,chunked\",\n \"gzip,chunked\",\n ):\n return None\n elif te in (\n \"compress\",\n \"deflate\",\n \"gzip\",\n \"identity\",\n ):\n if response:\n return -1\n else:\n raise ValueError(f\"Invalid request transfer encoding, message body cannot be determined reliably.\")\n else:\n raise ValueError(f\"Unknown transfer encoding: {headers['transfer-encoding']!r}\")",
" # 4. If a message is received without Transfer-Encoding and with\n # either multiple Content-Length header fields having differing\n # field-values or a single Content-Length header field having an\n # invalid value, then the message framing is invalid and the\n # recipient MUST treat it as an unrecoverable error. If this is a\n # request message, the server MUST respond with a 400 (Bad Request)\n # status code and then close the connection. If this is a response\n # message received by a proxy, the proxy MUST close the connection\n # to the server, discard the received response, and send a 502 (Bad\n # Gateway) response to the client. If this is a response message\n # received by a user agent, the user agent MUST close the\n # connection to the server and discard the received response.\n #\n # 5. If a valid Content-Length header field is present without\n # Transfer-Encoding, its decimal value defines the expected message\n # body length in octets. If the sender closes the connection or\n # the recipient times out before the indicated number of octets are\n # received, the recipient MUST consider the message to be\n # incomplete and close the connection.\n if \"content-length\" in headers:\n sizes = headers.get_all(\"content-length\")\n different_content_length_headers = any(x != sizes[0] for x in sizes)\n if different_content_length_headers:\n raise ValueError(f\"Conflicting Content-Length headers: {sizes!r}\")\n try:\n size = int(sizes[0])\n except ValueError:\n raise ValueError(f\"Invalid Content-Length header: {sizes[0]!r}\")\n if size < 0:\n raise ValueError(f\"Negative Content-Length header: {sizes[0]!r}\")\n return size",
" # 6. If this is a request message and none of the above are true, then\n # the message body length is zero (no message body is present).\n if not response:\n return 0",
" # 7. Otherwise, this is a response message without a declared message\n # body length, so the message body length is determined by the\n # number of octets received prior to the server closing the\n # connection.\n return -1",
"\ndef raise_if_http_version_unknown(http_version: bytes) -> None:\n if not re.match(br\"^HTTP/\\d\\.\\d$\", http_version):\n raise ValueError(f\"Unknown HTTP version: {http_version!r}\")",
"\ndef _read_request_line(line: bytes) -> Tuple[str, int, bytes, bytes, bytes, bytes, bytes]:\n try:\n method, target, http_version = line.split()\n port: Optional[int]",
" if target == b\"*\" or target.startswith(b\"/\"):\n scheme, authority, path = b\"\", b\"\", target\n host, port = \"\", 0\n elif method == b\"CONNECT\":\n scheme, authority, path = b\"\", target, b\"\"\n host, port = url.parse_authority(authority, check=True)\n if not port:\n raise ValueError\n else:\n scheme, rest = target.split(b\"://\", maxsplit=1)\n authority, _, path_ = rest.partition(b\"/\")\n path = b\"/\" + path_\n host, port = url.parse_authority(authority, check=True)\n port = port or url.default_port(scheme)\n if not port:\n raise ValueError\n # TODO: we can probably get rid of this check?\n url.parse(target)",
" raise_if_http_version_unknown(http_version)\n except ValueError as e:\n raise ValueError(f\"Bad HTTP request line: {line!r}\") from e",
" return host, port, method, scheme, authority, path, http_version",
"\ndef _read_response_line(line: bytes) -> Tuple[bytes, int, bytes]:\n try:\n parts = line.split(None, 2)\n if len(parts) == 2: # handle missing message gracefully\n parts.append(b\"\")",
" http_version, status_code_str, reason = parts\n status_code = int(status_code_str)\n raise_if_http_version_unknown(http_version)\n except ValueError as e:\n raise ValueError(f\"Bad HTTP response line: {line!r}\") from e",
" return http_version, status_code, reason",
"\ndef _read_headers(lines: Iterable[bytes]) -> Headers:\n \"\"\"\n Read a set of headers.\n Stop once a blank line is reached.",
" Returns:\n A headers object",
" Raises:\n exceptions.HttpSyntaxException\n \"\"\"\n ret: List[Tuple[bytes, bytes]] = []\n for line in lines:\n if line[0] in b\" \\t\":\n if not ret:\n raise ValueError(\"Invalid headers\")\n # continued header\n ret[-1] = (ret[-1][0], ret[-1][1] + b'\\r\\n ' + line.strip())\n else:\n try:\n name, value = line.split(b\":\", 1)\n value = value.strip()\n if not name:\n raise ValueError()\n ret.append((name, value))\n except ValueError:\n raise ValueError(f\"Invalid header line: {line!r}\")\n return Headers(ret)",
"\ndef read_request_head(lines: List[bytes]) -> Request:\n \"\"\"\n Parse an HTTP request head (request line + headers) from an iterable of lines",
" Args:\n lines: The input lines",
" Returns:\n The HTTP request object (without body)",
" Raises:\n ValueError: The input is malformed.\n \"\"\"\n host, port, method, scheme, authority, path, http_version = _read_request_line(lines[0])\n headers = _read_headers(lines[1:])",
" return Request(\n host=host,\n port=port,\n method=method,\n scheme=scheme,\n authority=authority,\n path=path,\n http_version=http_version,\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None\n )",
"\ndef read_response_head(lines: List[bytes]) -> Response:\n \"\"\"\n Parse an HTTP response head (response line + headers) from an iterable of lines",
" Args:\n lines: The input lines",
" Returns:\n The HTTP response object (without body)",
" Raises:\n ValueError: The input is malformed.\n \"\"\"\n http_version, status_code, reason = _read_response_line(lines[0])\n headers = _read_headers(lines[1:])",
" return Response(\n http_version=http_version,\n status_code=status_code,\n reason=reason,\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None,\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import abc\nfrom typing import Callable, Optional, Type, Union",
"import h11\nfrom h11._readers import ChunkedReader, ContentLengthReader, Http10Reader\nfrom h11._receivebuffer import ReceiveBuffer",
"from mitmproxy import http, version\nfrom mitmproxy.connection import Connection, ConnectionState\nfrom mitmproxy.net.http import http1, status_codes\nfrom mitmproxy.proxy import commands, events, layer\nfrom mitmproxy.proxy.layers.http._base import ReceiveHttp, StreamId\nfrom mitmproxy.proxy.utils import expect\nfrom mitmproxy.utils import human\nfrom ._base import HttpConnection, format_error\nfrom ._events import HttpEvent, RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \\\n ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError\nfrom ...context import Context",
"TBodyReader = Union[ChunkedReader, Http10Reader, ContentLengthReader]",
"\nclass Http1Connection(HttpConnection, metaclass=abc.ABCMeta):\n stream_id: Optional[StreamId] = None\n request: Optional[http.Request] = None\n response: Optional[http.Response] = None\n request_done: bool = False\n response_done: bool = False\n # this is a bit of a hack to make both mypy and PyCharm happy.\n state: Union[Callable[[events.Event], layer.CommandGenerator[None]], Callable]\n body_reader: TBodyReader\n buf: ReceiveBuffer",
" ReceiveProtocolError: Type[Union[RequestProtocolError, ResponseProtocolError]]\n ReceiveData: Type[Union[RequestData, ResponseData]]\n ReceiveEndOfMessage: Type[Union[RequestEndOfMessage, ResponseEndOfMessage]]",
" def __init__(self, context: Context, conn: Connection):\n super().__init__(context, conn)\n self.buf = ReceiveBuffer()",
" @abc.abstractmethod\n def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:\n yield from () # pragma: no cover",
" @abc.abstractmethod\n def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n yield from () # pragma: no cover",
" def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:\n if isinstance(event, HttpEvent):\n yield from self.send(event)\n else:\n if isinstance(event, events.DataReceived) and self.state != self.passthrough:\n self.buf += event.data\n yield from self.state(event)",
" @expect(events.Start)\n def start(self, _) -> layer.CommandGenerator[None]:\n self.state = self.read_headers\n yield from ()",
" state = start",
" def read_body(self, event: events.Event) -> layer.CommandGenerator[None]:\n assert self.stream_id\n while True:\n try:\n if isinstance(event, events.DataReceived):\n h11_event = self.body_reader(self.buf)\n elif isinstance(event, events.ConnectionClosed):\n h11_event = self.body_reader.read_eof()\n else:\n raise AssertionError(f\"Unexpected event: {event}\")\n except h11.ProtocolError as e:\n yield commands.CloseConnection(self.conn)\n yield ReceiveHttp(self.ReceiveProtocolError(self.stream_id, f\"HTTP/1 protocol error: {e}\"))\n return",
" if h11_event is None:\n return\n elif isinstance(h11_event, h11.Data):\n data: bytes = bytes(h11_event.data)\n if data:\n yield ReceiveHttp(self.ReceiveData(self.stream_id, data))\n elif isinstance(h11_event, h11.EndOfMessage):\n assert self.request\n if h11_event.headers:\n raise NotImplementedError(f\"HTTP trailers are not implemented yet.\")\n if self.request.data.method.upper() != b\"CONNECT\":\n yield ReceiveHttp(self.ReceiveEndOfMessage(self.stream_id))\n is_request = isinstance(self, Http1Server)\n yield from self.mark_done(\n request=is_request,\n response=not is_request\n )\n return",
" def wait(self, event: events.Event) -> layer.CommandGenerator[None]:\n \"\"\"\n We wait for the current flow to be finished before parsing the next message,\n as we may want to upgrade to WebSocket or plain TCP before that.\n \"\"\"\n assert self.stream_id\n if isinstance(event, events.DataReceived):\n return\n elif isinstance(event, events.ConnectionClosed):\n # for practical purposes, we assume that a peer which sent at least a FIN\n # is not interested in any more data from us, see\n # see https://github.com/httpwg/http-core/issues/22\n if event.connection.state is not ConnectionState.CLOSED:\n yield commands.CloseConnection(event.connection)\n yield ReceiveHttp(self.ReceiveProtocolError(self.stream_id, f\"Client disconnected.\",\n code=status_codes.CLIENT_CLOSED_REQUEST))\n else: # pragma: no cover\n raise AssertionError(f\"Unexpected event: {event}\")",
" def done(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n yield from () # pragma: no cover",
" def make_pipe(self) -> layer.CommandGenerator[None]:\n self.state = self.passthrough\n if self.buf:\n already_received = self.buf.maybe_extract_at_most(len(self.buf))\n # Some clients send superfluous newlines after CONNECT, we want to eat those.\n already_received = already_received.lstrip(b\"\\r\\n\")\n if already_received:\n yield from self.state(events.DataReceived(self.conn, already_received))",
" def passthrough(self, event: events.Event) -> layer.CommandGenerator[None]:\n assert self.stream_id\n if isinstance(event, events.DataReceived):\n yield ReceiveHttp(self.ReceiveData(self.stream_id, event.data))\n elif isinstance(event, events.ConnectionClosed):\n if isinstance(self, Http1Server):\n yield ReceiveHttp(RequestEndOfMessage(self.stream_id))\n else:\n yield ReceiveHttp(ResponseEndOfMessage(self.stream_id))",
" def mark_done(self, *, request: bool = False, response: bool = False) -> layer.CommandGenerator[None]:\n if request:\n self.request_done = True\n if response:\n self.response_done = True\n if self.request_done and self.response_done:\n assert self.request\n assert self.response\n if should_make_pipe(self.request, self.response):\n yield from self.make_pipe()\n return\n try:\n read_until_eof_semantics = http1.expected_http_body_size(self.request, self.response) == -1\n except ValueError:\n # this may raise only now (and not earlier) because an addon set invalid headers,\n # in which case it's not really clear what we are supposed to do.\n read_until_eof_semantics = False\n connection_done = (\n read_until_eof_semantics\n or http1.connection_close(self.request.http_version, self.request.headers)\n or http1.connection_close(self.response.http_version, self.response.headers)\n # If we proxy HTTP/2 to HTTP/1, we only use upstream connections for one request.\n # This simplifies our connection management quite a bit as we can rely on\n # the proxyserver's max-connection-per-server throttling.\n or (self.request.is_http2 and isinstance(self, Http1Client))\n )\n if connection_done:\n yield commands.CloseConnection(self.conn)\n self.state = self.done\n return\n self.request_done = self.response_done = False\n self.request = self.response = None\n if isinstance(self, Http1Server):\n self.stream_id += 2\n else:\n self.stream_id = None\n self.state = self.read_headers\n if self.buf:\n yield from self.state(events.DataReceived(self.conn, b\"\"))",
"\nclass Http1Server(Http1Connection):\n \"\"\"A simple HTTP/1 server with no pipelining support.\"\"\"",
" ReceiveProtocolError = RequestProtocolError\n ReceiveData = RequestData\n ReceiveEndOfMessage = RequestEndOfMessage\n stream_id: int",
" def __init__(self, context: Context):\n super().__init__(context, context.client)\n self.stream_id = 1",
" def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:\n assert event.stream_id == self.stream_id\n if isinstance(event, ResponseHeaders):\n self.response = response = event.response",
" if response.is_http2:\n response = response.copy()\n # Convert to an HTTP/1 response.\n response.http_version = \"HTTP/1.1\"\n # not everyone supports empty reason phrases, so we better make up one.\n response.reason = status_codes.RESPONSES.get(response.status_code, \"\")\n # Shall we set a Content-Length header here if there is none?\n # For now, let's try to modify as little as possible.",
" raw = http1.assemble_response_head(response)\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, ResponseData):\n assert self.response\n if \"chunked\" in self.response.headers.get(\"transfer-encoding\", \"\").lower():\n raw = b\"%x\\r\\n%s\\r\\n\" % (len(event.data), event.data)\n else:\n raw = event.data\n if raw:\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, ResponseEndOfMessage):\n assert self.response\n if \"chunked\" in self.response.headers.get(\"transfer-encoding\", \"\").lower():\n yield commands.SendData(self.conn, b\"0\\r\\n\\r\\n\")\n yield from self.mark_done(response=True)\n elif isinstance(event, ResponseProtocolError):\n if not self.response and event.code != status_codes.NO_RESPONSE:\n yield commands.SendData(self.conn, make_error_response(event.code, event.message))\n if self.conn.state & ConnectionState.CAN_WRITE:\n yield commands.CloseConnection(self.conn)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
" def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n if isinstance(event, events.DataReceived):\n request_head = self.buf.maybe_extract_lines()\n if request_head:\n request_head = [bytes(x) for x in request_head] # TODO: Make url.parse compatible with bytearrays\n try:\n self.request = http1.read_request_head(request_head)",
"",
" expected_body_size = http1.expected_http_body_size(self.request)\n except ValueError as e:\n yield commands.SendData(self.conn, make_error_response(400, str(e)))\n yield commands.CloseConnection(self.conn)\n if self.request:\n # we have headers that we can show in the ui\n yield ReceiveHttp(RequestHeaders(self.stream_id, self.request, False))\n yield ReceiveHttp(RequestProtocolError(self.stream_id, str(e), 400))\n else:\n yield commands.Log(f\"{human.format_address(self.conn.peername)}: {e}\")\n self.state = self.done\n return\n yield ReceiveHttp(RequestHeaders(self.stream_id, self.request, expected_body_size == 0))\n self.body_reader = make_body_reader(expected_body_size)\n self.state = self.read_body\n yield from self.state(event)\n else:\n pass # FIXME: protect against header size DoS\n elif isinstance(event, events.ConnectionClosed):\n buf = bytes(self.buf)\n if buf.strip():\n yield commands.Log(f\"Client closed connection before completing request headers: {buf!r}\")\n yield commands.CloseConnection(self.conn)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
" def mark_done(self, *, request: bool = False, response: bool = False) -> layer.CommandGenerator[None]:\n yield from super().mark_done(request=request, response=response)\n if self.request_done and not self.response_done:\n self.state = self.wait",
"\nclass Http1Client(Http1Connection):\n \"\"\"A simple HTTP/1 client with no pipelining support.\"\"\"",
" ReceiveProtocolError = ResponseProtocolError\n ReceiveData = ResponseData\n ReceiveEndOfMessage = ResponseEndOfMessage",
" def __init__(self, context: Context):\n super().__init__(context, context.server)",
" def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:\n if isinstance(event, RequestProtocolError):\n yield commands.CloseConnection(self.conn)\n return",
" if not self.stream_id:\n assert isinstance(event, RequestHeaders)\n self.stream_id = event.stream_id\n self.request = event.request\n assert self.stream_id == event.stream_id",
" if isinstance(event, RequestHeaders):\n request = event.request\n if request.is_http2:\n # Convert to an HTTP/1 request.\n request = request.copy() # (we could probably be a bit more efficient here.)\n request.http_version = \"HTTP/1.1\"\n if \"Host\" not in request.headers and request.authority:\n request.headers.insert(0, \"Host\", request.authority)\n request.authority = \"\"\n raw = http1.assemble_request_head(request)\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, RequestData):\n assert self.request\n if \"chunked\" in self.request.headers.get(\"transfer-encoding\", \"\").lower():\n raw = b\"%x\\r\\n%s\\r\\n\" % (len(event.data), event.data)\n else:\n raw = event.data\n if raw:\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, RequestEndOfMessage):\n assert self.request\n if \"chunked\" in self.request.headers.get(\"transfer-encoding\", \"\").lower():\n yield commands.SendData(self.conn, b\"0\\r\\n\\r\\n\")\n elif http1.expected_http_body_size(self.request, self.response) == -1:\n yield commands.CloseConnection(self.conn, half_close=True)\n yield from self.mark_done(request=True)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
" def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n if isinstance(event, events.DataReceived):\n if not self.request:\n # we just received some data for an unknown request.\n yield commands.Log(f\"Unexpected data from server: {bytes(self.buf)!r}\")\n yield commands.CloseConnection(self.conn)\n return\n assert self.stream_id",
" response_head = self.buf.maybe_extract_lines()\n if response_head:\n response_head = [bytes(x) for x in response_head] # TODO: Make url.parse compatible with bytearrays\n try:\n self.response = http1.read_response_head(response_head)",
"",
" expected_size = http1.expected_http_body_size(self.request, self.response)\n except ValueError as e:\n yield commands.CloseConnection(self.conn)\n yield ReceiveHttp(ResponseProtocolError(self.stream_id, f\"Cannot parse HTTP response: {e}\"))\n return\n yield ReceiveHttp(ResponseHeaders(self.stream_id, self.response, expected_size == 0))\n self.body_reader = make_body_reader(expected_size)",
" self.state = self.read_body\n yield from self.state(event)\n else:\n pass # FIXME: protect against header size DoS\n elif isinstance(event, events.ConnectionClosed):\n if self.conn.state & ConnectionState.CAN_WRITE:\n yield commands.CloseConnection(self.conn)\n if self.stream_id:\n if self.buf:\n yield ReceiveHttp(ResponseProtocolError(self.stream_id,\n f\"unexpected server response: {bytes(self.buf)!r}\"))\n else:\n # The server has closed the connection to prevent us from continuing.\n # We need to signal that to the stream.\n # https://tools.ietf.org/html/rfc7231#section-6.5.11\n yield ReceiveHttp(ResponseProtocolError(self.stream_id, \"server closed connection\"))\n else:\n return\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
"\ndef should_make_pipe(request: http.Request, response: http.Response) -> bool:\n if response.status_code == 101:\n return True\n elif response.status_code == 200 and request.method.upper() == \"CONNECT\":\n return True\n else:\n return False",
"\ndef make_body_reader(expected_size: Optional[int]) -> TBodyReader:\n if expected_size is None:\n return ChunkedReader()\n elif expected_size == -1:\n return Http10Reader()\n else:\n return ContentLengthReader(expected_size)",
"\ndef make_error_response(\n status_code: int,\n message: str = \"\",\n) -> bytes:\n resp = http.Response.make(\n status_code,\n format_error(status_code, message),\n http.Headers(\n Server=version.MITMPROXY,\n Connection=\"close\",\n Content_Type=\"text/html\",\n )\n )\n return http1.assemble_response(resp)",
"\n__all__ = [\n \"Http1Client\",\n \"Http1Server\",\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,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import abc\nfrom typing import Callable, Optional, Type, Union",
"import h11\nfrom h11._readers import ChunkedReader, ContentLengthReader, Http10Reader\nfrom h11._receivebuffer import ReceiveBuffer",
"from mitmproxy import http, version\nfrom mitmproxy.connection import Connection, ConnectionState\nfrom mitmproxy.net.http import http1, status_codes\nfrom mitmproxy.proxy import commands, events, layer\nfrom mitmproxy.proxy.layers.http._base import ReceiveHttp, StreamId\nfrom mitmproxy.proxy.utils import expect\nfrom mitmproxy.utils import human\nfrom ._base import HttpConnection, format_error\nfrom ._events import HttpEvent, RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \\\n ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError\nfrom ...context import Context",
"TBodyReader = Union[ChunkedReader, Http10Reader, ContentLengthReader]",
"\nclass Http1Connection(HttpConnection, metaclass=abc.ABCMeta):\n stream_id: Optional[StreamId] = None\n request: Optional[http.Request] = None\n response: Optional[http.Response] = None\n request_done: bool = False\n response_done: bool = False\n # this is a bit of a hack to make both mypy and PyCharm happy.\n state: Union[Callable[[events.Event], layer.CommandGenerator[None]], Callable]\n body_reader: TBodyReader\n buf: ReceiveBuffer",
" ReceiveProtocolError: Type[Union[RequestProtocolError, ResponseProtocolError]]\n ReceiveData: Type[Union[RequestData, ResponseData]]\n ReceiveEndOfMessage: Type[Union[RequestEndOfMessage, ResponseEndOfMessage]]",
" def __init__(self, context: Context, conn: Connection):\n super().__init__(context, conn)\n self.buf = ReceiveBuffer()",
" @abc.abstractmethod\n def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:\n yield from () # pragma: no cover",
" @abc.abstractmethod\n def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n yield from () # pragma: no cover",
" def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:\n if isinstance(event, HttpEvent):\n yield from self.send(event)\n else:\n if isinstance(event, events.DataReceived) and self.state != self.passthrough:\n self.buf += event.data\n yield from self.state(event)",
" @expect(events.Start)\n def start(self, _) -> layer.CommandGenerator[None]:\n self.state = self.read_headers\n yield from ()",
" state = start",
" def read_body(self, event: events.Event) -> layer.CommandGenerator[None]:\n assert self.stream_id\n while True:\n try:\n if isinstance(event, events.DataReceived):\n h11_event = self.body_reader(self.buf)\n elif isinstance(event, events.ConnectionClosed):\n h11_event = self.body_reader.read_eof()\n else:\n raise AssertionError(f\"Unexpected event: {event}\")\n except h11.ProtocolError as e:\n yield commands.CloseConnection(self.conn)\n yield ReceiveHttp(self.ReceiveProtocolError(self.stream_id, f\"HTTP/1 protocol error: {e}\"))\n return",
" if h11_event is None:\n return\n elif isinstance(h11_event, h11.Data):\n data: bytes = bytes(h11_event.data)\n if data:\n yield ReceiveHttp(self.ReceiveData(self.stream_id, data))\n elif isinstance(h11_event, h11.EndOfMessage):\n assert self.request\n if h11_event.headers:\n raise NotImplementedError(f\"HTTP trailers are not implemented yet.\")\n if self.request.data.method.upper() != b\"CONNECT\":\n yield ReceiveHttp(self.ReceiveEndOfMessage(self.stream_id))\n is_request = isinstance(self, Http1Server)\n yield from self.mark_done(\n request=is_request,\n response=not is_request\n )\n return",
" def wait(self, event: events.Event) -> layer.CommandGenerator[None]:\n \"\"\"\n We wait for the current flow to be finished before parsing the next message,\n as we may want to upgrade to WebSocket or plain TCP before that.\n \"\"\"\n assert self.stream_id\n if isinstance(event, events.DataReceived):\n return\n elif isinstance(event, events.ConnectionClosed):\n # for practical purposes, we assume that a peer which sent at least a FIN\n # is not interested in any more data from us, see\n # see https://github.com/httpwg/http-core/issues/22\n if event.connection.state is not ConnectionState.CLOSED:\n yield commands.CloseConnection(event.connection)\n yield ReceiveHttp(self.ReceiveProtocolError(self.stream_id, f\"Client disconnected.\",\n code=status_codes.CLIENT_CLOSED_REQUEST))\n else: # pragma: no cover\n raise AssertionError(f\"Unexpected event: {event}\")",
" def done(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n yield from () # pragma: no cover",
" def make_pipe(self) -> layer.CommandGenerator[None]:\n self.state = self.passthrough\n if self.buf:\n already_received = self.buf.maybe_extract_at_most(len(self.buf))\n # Some clients send superfluous newlines after CONNECT, we want to eat those.\n already_received = already_received.lstrip(b\"\\r\\n\")\n if already_received:\n yield from self.state(events.DataReceived(self.conn, already_received))",
" def passthrough(self, event: events.Event) -> layer.CommandGenerator[None]:\n assert self.stream_id\n if isinstance(event, events.DataReceived):\n yield ReceiveHttp(self.ReceiveData(self.stream_id, event.data))\n elif isinstance(event, events.ConnectionClosed):\n if isinstance(self, Http1Server):\n yield ReceiveHttp(RequestEndOfMessage(self.stream_id))\n else:\n yield ReceiveHttp(ResponseEndOfMessage(self.stream_id))",
" def mark_done(self, *, request: bool = False, response: bool = False) -> layer.CommandGenerator[None]:\n if request:\n self.request_done = True\n if response:\n self.response_done = True\n if self.request_done and self.response_done:\n assert self.request\n assert self.response\n if should_make_pipe(self.request, self.response):\n yield from self.make_pipe()\n return\n try:\n read_until_eof_semantics = http1.expected_http_body_size(self.request, self.response) == -1\n except ValueError:\n # this may raise only now (and not earlier) because an addon set invalid headers,\n # in which case it's not really clear what we are supposed to do.\n read_until_eof_semantics = False\n connection_done = (\n read_until_eof_semantics\n or http1.connection_close(self.request.http_version, self.request.headers)\n or http1.connection_close(self.response.http_version, self.response.headers)\n # If we proxy HTTP/2 to HTTP/1, we only use upstream connections for one request.\n # This simplifies our connection management quite a bit as we can rely on\n # the proxyserver's max-connection-per-server throttling.\n or (self.request.is_http2 and isinstance(self, Http1Client))\n )\n if connection_done:\n yield commands.CloseConnection(self.conn)\n self.state = self.done\n return\n self.request_done = self.response_done = False\n self.request = self.response = None\n if isinstance(self, Http1Server):\n self.stream_id += 2\n else:\n self.stream_id = None\n self.state = self.read_headers\n if self.buf:\n yield from self.state(events.DataReceived(self.conn, b\"\"))",
"\nclass Http1Server(Http1Connection):\n \"\"\"A simple HTTP/1 server with no pipelining support.\"\"\"",
" ReceiveProtocolError = RequestProtocolError\n ReceiveData = RequestData\n ReceiveEndOfMessage = RequestEndOfMessage\n stream_id: int",
" def __init__(self, context: Context):\n super().__init__(context, context.client)\n self.stream_id = 1",
" def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:\n assert event.stream_id == self.stream_id\n if isinstance(event, ResponseHeaders):\n self.response = response = event.response",
" if response.is_http2:\n response = response.copy()\n # Convert to an HTTP/1 response.\n response.http_version = \"HTTP/1.1\"\n # not everyone supports empty reason phrases, so we better make up one.\n response.reason = status_codes.RESPONSES.get(response.status_code, \"\")\n # Shall we set a Content-Length header here if there is none?\n # For now, let's try to modify as little as possible.",
" raw = http1.assemble_response_head(response)\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, ResponseData):\n assert self.response\n if \"chunked\" in self.response.headers.get(\"transfer-encoding\", \"\").lower():\n raw = b\"%x\\r\\n%s\\r\\n\" % (len(event.data), event.data)\n else:\n raw = event.data\n if raw:\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, ResponseEndOfMessage):\n assert self.response\n if \"chunked\" in self.response.headers.get(\"transfer-encoding\", \"\").lower():\n yield commands.SendData(self.conn, b\"0\\r\\n\\r\\n\")\n yield from self.mark_done(response=True)\n elif isinstance(event, ResponseProtocolError):\n if not self.response and event.code != status_codes.NO_RESPONSE:\n yield commands.SendData(self.conn, make_error_response(event.code, event.message))\n if self.conn.state & ConnectionState.CAN_WRITE:\n yield commands.CloseConnection(self.conn)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
" def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n if isinstance(event, events.DataReceived):\n request_head = self.buf.maybe_extract_lines()\n if request_head:\n request_head = [bytes(x) for x in request_head] # TODO: Make url.parse compatible with bytearrays\n try:\n self.request = http1.read_request_head(request_head)",
" if self.context.options.validate_inbound_headers:\n http1.validate_headers(self.request.headers)",
" expected_body_size = http1.expected_http_body_size(self.request)\n except ValueError as e:\n yield commands.SendData(self.conn, make_error_response(400, str(e)))\n yield commands.CloseConnection(self.conn)\n if self.request:\n # we have headers that we can show in the ui\n yield ReceiveHttp(RequestHeaders(self.stream_id, self.request, False))\n yield ReceiveHttp(RequestProtocolError(self.stream_id, str(e), 400))\n else:\n yield commands.Log(f\"{human.format_address(self.conn.peername)}: {e}\")\n self.state = self.done\n return\n yield ReceiveHttp(RequestHeaders(self.stream_id, self.request, expected_body_size == 0))\n self.body_reader = make_body_reader(expected_body_size)\n self.state = self.read_body\n yield from self.state(event)\n else:\n pass # FIXME: protect against header size DoS\n elif isinstance(event, events.ConnectionClosed):\n buf = bytes(self.buf)\n if buf.strip():\n yield commands.Log(f\"Client closed connection before completing request headers: {buf!r}\")\n yield commands.CloseConnection(self.conn)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
" def mark_done(self, *, request: bool = False, response: bool = False) -> layer.CommandGenerator[None]:\n yield from super().mark_done(request=request, response=response)\n if self.request_done and not self.response_done:\n self.state = self.wait",
"\nclass Http1Client(Http1Connection):\n \"\"\"A simple HTTP/1 client with no pipelining support.\"\"\"",
" ReceiveProtocolError = ResponseProtocolError\n ReceiveData = ResponseData\n ReceiveEndOfMessage = ResponseEndOfMessage",
" def __init__(self, context: Context):\n super().__init__(context, context.server)",
" def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:\n if isinstance(event, RequestProtocolError):\n yield commands.CloseConnection(self.conn)\n return",
" if not self.stream_id:\n assert isinstance(event, RequestHeaders)\n self.stream_id = event.stream_id\n self.request = event.request\n assert self.stream_id == event.stream_id",
" if isinstance(event, RequestHeaders):\n request = event.request\n if request.is_http2:\n # Convert to an HTTP/1 request.\n request = request.copy() # (we could probably be a bit more efficient here.)\n request.http_version = \"HTTP/1.1\"\n if \"Host\" not in request.headers and request.authority:\n request.headers.insert(0, \"Host\", request.authority)\n request.authority = \"\"\n raw = http1.assemble_request_head(request)\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, RequestData):\n assert self.request\n if \"chunked\" in self.request.headers.get(\"transfer-encoding\", \"\").lower():\n raw = b\"%x\\r\\n%s\\r\\n\" % (len(event.data), event.data)\n else:\n raw = event.data\n if raw:\n yield commands.SendData(self.conn, raw)\n elif isinstance(event, RequestEndOfMessage):\n assert self.request\n if \"chunked\" in self.request.headers.get(\"transfer-encoding\", \"\").lower():\n yield commands.SendData(self.conn, b\"0\\r\\n\\r\\n\")\n elif http1.expected_http_body_size(self.request, self.response) == -1:\n yield commands.CloseConnection(self.conn, half_close=True)\n yield from self.mark_done(request=True)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
" def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:\n if isinstance(event, events.DataReceived):\n if not self.request:\n # we just received some data for an unknown request.\n yield commands.Log(f\"Unexpected data from server: {bytes(self.buf)!r}\")\n yield commands.CloseConnection(self.conn)\n return\n assert self.stream_id",
" response_head = self.buf.maybe_extract_lines()\n if response_head:\n response_head = [bytes(x) for x in response_head] # TODO: Make url.parse compatible with bytearrays\n try:\n self.response = http1.read_response_head(response_head)",
" if self.context.options.validate_inbound_headers:\n http1.validate_headers(self.response.headers)",
" expected_size = http1.expected_http_body_size(self.request, self.response)\n except ValueError as e:\n yield commands.CloseConnection(self.conn)\n yield ReceiveHttp(ResponseProtocolError(self.stream_id, f\"Cannot parse HTTP response: {e}\"))\n return\n yield ReceiveHttp(ResponseHeaders(self.stream_id, self.response, expected_size == 0))\n self.body_reader = make_body_reader(expected_size)",
" self.state = self.read_body\n yield from self.state(event)\n else:\n pass # FIXME: protect against header size DoS\n elif isinstance(event, events.ConnectionClosed):\n if self.conn.state & ConnectionState.CAN_WRITE:\n yield commands.CloseConnection(self.conn)\n if self.stream_id:\n if self.buf:\n yield ReceiveHttp(ResponseProtocolError(self.stream_id,\n f\"unexpected server response: {bytes(self.buf)!r}\"))\n else:\n # The server has closed the connection to prevent us from continuing.\n # We need to signal that to the stream.\n # https://tools.ietf.org/html/rfc7231#section-6.5.11\n yield ReceiveHttp(ResponseProtocolError(self.stream_id, \"server closed connection\"))\n else:\n return\n else:\n raise AssertionError(f\"Unexpected event: {event}\")",
"\ndef should_make_pipe(request: http.Request, response: http.Response) -> bool:\n if response.status_code == 101:\n return True\n elif response.status_code == 200 and request.method.upper() == \"CONNECT\":\n return True\n else:\n return False",
"\ndef make_body_reader(expected_size: Optional[int]) -> TBodyReader:\n if expected_size is None:\n return ChunkedReader()\n elif expected_size == -1:\n return Http10Reader()\n else:\n return ContentLengthReader(expected_size)",
"\ndef make_error_response(\n status_code: int,\n message: str = \"\",\n) -> bytes:\n resp = http.Response.make(\n status_code,\n format_error(status_code, message),\n http.Headers(\n Server=version.MITMPROXY,\n Connection=\"close\",\n Content_Type=\"text/html\",\n )\n )\n return http1.assemble_response(resp)",
"\n__all__ = [\n \"Http1Client\",\n \"Http1Server\",\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import collections\nimport time\nfrom enum import Enum\nfrom typing import ClassVar, DefaultDict, Dict, List, Optional, Sequence, Tuple, Type, Union",
"import h2.config\nimport h2.connection\nimport h2.errors\nimport h2.events\nimport h2.exceptions\nimport h2.settings\nimport h2.stream\nimport h2.utilities",
"from mitmproxy import http, version\nfrom mitmproxy.connection import Connection\nfrom mitmproxy.net.http import status_codes, url\nfrom mitmproxy.utils import human\nfrom . import RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \\\n ResponseEndOfMessage, ResponseHeaders, RequestTrailers, ResponseTrailers, ResponseProtocolError\nfrom ._base import HttpConnection, HttpEvent, ReceiveHttp, format_error\nfrom ._http_h2 import BufferedH2Connection, H2ConnectionLogger\nfrom ...commands import CloseConnection, Log, SendData\nfrom ...context import Context\nfrom ...events import ConnectionClosed, DataReceived, Event, Start\nfrom ...layer import CommandGenerator\nfrom ...utils import expect",
"\nclass StreamState(Enum):\n EXPECTING_HEADERS = 1\n HEADERS_RECEIVED = 2",
"\nCATCH_HYPER_H2_ERRORS = (ValueError, IndexError)",
"\nclass Http2Connection(HttpConnection):\n h2_conf: ClassVar[h2.config.H2Configuration]\n h2_conf_defaults = dict(\n header_encoding=False,\n validate_outbound_headers=False,",
" validate_inbound_headers=True,",
" normalize_inbound_headers=False, # changing this to True is required to pass h2spec\n normalize_outbound_headers=False,\n )\n h2_conn: BufferedH2Connection\n streams: Dict[int, StreamState]\n \"\"\"keep track of all active stream ids to send protocol errors on teardown\"\"\"",
" ReceiveProtocolError: Type[Union[RequestProtocolError, ResponseProtocolError]]\n ReceiveData: Type[Union[RequestData, ResponseData]]\n ReceiveTrailers: Type[Union[RequestTrailers, ResponseTrailers]]\n ReceiveEndOfMessage: Type[Union[RequestEndOfMessage, ResponseEndOfMessage]]",
" def __init__(self, context: Context, conn: Connection):\n super().__init__(context, conn)\n if self.debug:\n self.h2_conf.logger = H2ConnectionLogger(f\"{human.format_address(self.context.client.peername)}: \"\n f\"{self.__class__.__name__}\")",
"",
" self.h2_conn = BufferedH2Connection(self.h2_conf)\n self.streams = {}",
" def is_closed(self, stream_id: int) -> bool:\n \"\"\"Check if a non-idle stream is closed\"\"\"\n stream = self.h2_conn.streams.get(stream_id, None)\n if (\n stream is not None\n and\n stream.state_machine.state is not h2.stream.StreamState.CLOSED\n and\n self.h2_conn.state_machine.state is not h2.connection.ConnectionState.CLOSED\n ):\n return False\n else:\n return True",
" def is_open_for_us(self, stream_id: int) -> bool:\n \"\"\"Check if we can write to a non-idle stream.\"\"\"\n stream = self.h2_conn.streams.get(stream_id, None)\n if (\n stream is not None\n and\n stream.state_machine.state is not h2.stream.StreamState.HALF_CLOSED_LOCAL\n and\n stream.state_machine.state is not h2.stream.StreamState.CLOSED\n and\n self.h2_conn.state_machine.state is not h2.connection.ConnectionState.CLOSED\n ):\n return True\n else:\n return False",
" def _handle_event(self, event: Event) -> CommandGenerator[None]:\n if isinstance(event, Start):\n self.h2_conn.initiate_connection()\n yield SendData(self.conn, self.h2_conn.data_to_send())",
" elif isinstance(event, HttpEvent):\n if isinstance(event, (RequestData, ResponseData)):\n if self.is_open_for_us(event.stream_id):\n self.h2_conn.send_data(event.stream_id, event.data)\n elif isinstance(event, (RequestTrailers, ResponseTrailers)):\n if self.is_open_for_us(event.stream_id):\n trailers = [*event.trailers.fields]\n self.h2_conn.send_headers(event.stream_id, trailers, end_stream=True)\n elif isinstance(event, (RequestEndOfMessage, ResponseEndOfMessage)):\n if self.is_open_for_us(event.stream_id):\n self.h2_conn.end_stream(event.stream_id)\n elif isinstance(event, (RequestProtocolError, ResponseProtocolError)):\n if not self.is_closed(event.stream_id):\n code = {\n status_codes.CLIENT_CLOSED_REQUEST: h2.errors.ErrorCodes.CANCEL,\n }.get(event.code, h2.errors.ErrorCodes.INTERNAL_ERROR)\n stream: h2.stream.H2Stream = self.h2_conn.streams[event.stream_id]\n send_error_message = (\n isinstance(event, ResponseProtocolError)\n and self.is_open_for_us(event.stream_id)\n and not stream.state_machine.headers_sent\n and event.code != status_codes.NO_RESPONSE\n )\n if send_error_message:\n self.h2_conn.send_headers(event.stream_id, [\n (b\":status\", b\"%d\" % event.code),\n (b\"server\", version.MITMPROXY.encode()),\n (b\"content-type\", b\"text/html\"),\n ])\n self.h2_conn.send_data(\n event.stream_id,\n format_error(event.code, event.message),\n end_stream=True\n )\n else:\n self.h2_conn.reset_stream(event.stream_id, code)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")\n data_to_send = self.h2_conn.data_to_send()\n if data_to_send:\n yield SendData(self.conn, data_to_send)",
" elif isinstance(event, DataReceived):\n try:\n try:\n events = self.h2_conn.receive_data(event.data)\n except CATCH_HYPER_H2_ERRORS as e: # pragma: no cover\n # this should never raise a ValueError, but we triggered one while fuzzing:\n # https://github.com/python-hyper/hyper-h2/issues/1231\n # this stays here as defense-in-depth.\n raise h2.exceptions.ProtocolError(f\"uncaught hyper-h2 error: {e}\") from e\n except h2.exceptions.ProtocolError as e:\n events = [e]",
" for h2_event in events:\n if self.debug:\n yield Log(f\"{self.debug}[h2] {h2_event}\", \"debug\")\n if (yield from self.handle_h2_event(h2_event)):\n if self.debug:\n yield Log(f\"{self.debug}[h2] done\", \"debug\")\n return",
" data_to_send = self.h2_conn.data_to_send()\n if data_to_send:\n yield SendData(self.conn, data_to_send)",
" elif isinstance(event, ConnectionClosed):\n yield from self.close_connection(\"peer closed connection\")\n else:\n raise AssertionError(f\"Unexpected event: {event!r}\")",
" def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:\n \"\"\"returns true if further processing should be stopped.\"\"\"\n if isinstance(event, h2.events.DataReceived):\n state = self.streams.get(event.stream_id, None)\n if state is StreamState.HEADERS_RECEIVED:\n yield ReceiveHttp(self.ReceiveData(event.stream_id, event.data))\n elif state is StreamState.EXPECTING_HEADERS:\n yield from self.protocol_error(f\"Received HTTP/2 data frame, expected headers.\")\n return True\n self.h2_conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)\n elif isinstance(event, h2.events.TrailersReceived):\n trailers = http.Headers(event.headers)\n yield ReceiveHttp(self.ReceiveTrailers(event.stream_id, trailers))\n elif isinstance(event, h2.events.StreamEnded):\n state = self.streams.get(event.stream_id, None)\n if state is StreamState.HEADERS_RECEIVED:\n yield ReceiveHttp(self.ReceiveEndOfMessage(event.stream_id))\n elif state is StreamState.EXPECTING_HEADERS:\n raise AssertionError(\"unreachable\")\n if self.is_closed(event.stream_id):\n self.streams.pop(event.stream_id, None)\n elif isinstance(event, h2.events.StreamReset):\n if event.stream_id in self.streams:\n try:\n err_str = h2.errors.ErrorCodes(event.error_code).name\n except ValueError:\n err_str = str(event.error_code)\n err_code = {\n h2.errors.ErrorCodes.CANCEL: status_codes.CLIENT_CLOSED_REQUEST,\n }.get(event.error_code, self.ReceiveProtocolError.code)\n yield ReceiveHttp(self.ReceiveProtocolError(event.stream_id, f\"stream reset by client ({err_str})\",\n code=err_code))\n self.streams.pop(event.stream_id)\n else:\n pass # We don't track priority frames which could be followed by a stream reset here.\n elif isinstance(event, h2.exceptions.ProtocolError):\n yield from self.protocol_error(f\"HTTP/2 protocol error: {event}\")\n return True\n elif isinstance(event, h2.events.ConnectionTerminated):\n yield from self.close_connection(f\"HTTP/2 connection closed: {event!r}\")\n return True\n # The implementation above isn't really ideal, we should probably only terminate streams > last_stream_id?\n # We currently lack a mechanism to signal that connections are still active but cannot be reused.\n # for stream_id in self.streams:\n # if stream_id > event.last_stream_id:\n # yield ReceiveHttp(self.ReceiveProtocolError(stream_id, f\"HTTP/2 connection closed: {event!r}\"))\n # self.streams.pop(stream_id)\n elif isinstance(event, h2.events.RemoteSettingsChanged):\n pass\n elif isinstance(event, h2.events.SettingsAcknowledged):\n pass\n elif isinstance(event, h2.events.PriorityUpdated):\n pass\n elif isinstance(event, h2.events.PingReceived):\n pass\n elif isinstance(event, h2.events.PingAckReceived):\n pass\n elif isinstance(event, h2.events.PushedStreamReceived):\n yield Log(\"Received HTTP/2 push promise, even though we signalled no support.\", \"error\")\n elif isinstance(event, h2.events.UnknownFrameReceived):\n # https://http2.github.io/http2-spec/#rfc.section.4.1\n # Implementations MUST ignore and discard any frame that has a type that is unknown.\n yield Log(f\"Ignoring unknown HTTP/2 frame type: {event.frame.type}\")\n else:\n raise AssertionError(f\"Unexpected event: {event!r}\")\n return False",
" def protocol_error(\n self,\n message: str,\n error_code: int = h2.errors.ErrorCodes.PROTOCOL_ERROR,\n ) -> CommandGenerator[None]:\n yield Log(f\"{human.format_address(self.conn.peername)}: {message}\")\n self.h2_conn.close_connection(error_code, message.encode())\n yield SendData(self.conn, self.h2_conn.data_to_send())\n yield from self.close_connection(message)",
" def close_connection(self, msg: str) -> CommandGenerator[None]:\n yield CloseConnection(self.conn)\n for stream_id in self.streams:\n yield ReceiveHttp(self.ReceiveProtocolError(stream_id, msg))\n self.streams.clear()\n self._handle_event = self.done # type: ignore",
" @expect(DataReceived, HttpEvent, ConnectionClosed)\n def done(self, _) -> CommandGenerator[None]:\n yield from ()",
"\ndef normalize_h1_headers(headers: List[Tuple[bytes, bytes]], is_client: bool) -> List[Tuple[bytes, bytes]]:\n # HTTP/1 servers commonly send capitalized headers (Content-Length vs content-length),\n # which isn't valid HTTP/2. As such we normalize.\n headers = h2.utilities.normalize_outbound_headers(\n headers,\n h2.utilities.HeaderValidationFlags(is_client, False, not is_client, False)\n )\n # make sure that this is not just an iterator but an iterable,\n # otherwise hyper-h2 will silently drop headers.\n headers = list(headers)\n return headers",
"\ndef normalize_h2_headers(headers: List[Tuple[bytes, bytes]]) -> CommandGenerator[None]:\n for i in range(len(headers)):\n if not headers[i][0].islower():\n yield Log(f\"Lowercased {repr(headers[i][0]).lstrip('b')} header as uppercase is not allowed with HTTP/2.\")\n headers[i] = (headers[i][0].lower(), headers[i][1])",
"\nclass Http2Server(Http2Connection):\n h2_conf = h2.config.H2Configuration(\n **Http2Connection.h2_conf_defaults,\n client_side=False,\n )",
" ReceiveProtocolError = RequestProtocolError\n ReceiveData = RequestData\n ReceiveTrailers = RequestTrailers\n ReceiveEndOfMessage = RequestEndOfMessage",
" def __init__(self, context: Context):\n super().__init__(context, context.client)",
" def _handle_event(self, event: Event) -> CommandGenerator[None]:\n if isinstance(event, ResponseHeaders):\n if self.is_open_for_us(event.stream_id):\n headers = [\n (b\":status\", b\"%d\" % event.response.status_code),\n *event.response.headers.fields\n ]\n if event.response.is_http2:\n if self.context.options.normalize_outbound_headers:\n yield from normalize_h2_headers(headers)\n else:\n headers = normalize_h1_headers(headers, False)",
" self.h2_conn.send_headers(\n event.stream_id,\n headers,\n end_stream=event.end_stream,\n )\n yield SendData(self.conn, self.h2_conn.data_to_send())\n else:\n yield from super()._handle_event(event)",
" def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:\n if isinstance(event, h2.events.RequestReceived):\n try:\n host, port, method, scheme, authority, path, headers = parse_h2_request_headers(event.headers)\n except ValueError as e:\n yield from self.protocol_error(f\"Invalid HTTP/2 request headers: {e}\")\n return True\n request = http.Request(\n host=host,\n port=port,\n method=method,\n scheme=scheme,\n authority=authority,\n path=path,\n http_version=b\"HTTP/2.0\",\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None,\n )\n self.streams[event.stream_id] = StreamState.HEADERS_RECEIVED\n yield ReceiveHttp(RequestHeaders(event.stream_id, request, end_stream=bool(event.stream_ended)))\n return False\n else:\n return (yield from super().handle_h2_event(event))",
"\nclass Http2Client(Http2Connection):\n h2_conf = h2.config.H2Configuration(\n **Http2Connection.h2_conf_defaults,\n client_side=True,\n )",
" ReceiveProtocolError = ResponseProtocolError\n ReceiveData = ResponseData\n ReceiveTrailers = ResponseTrailers\n ReceiveEndOfMessage = ResponseEndOfMessage",
" our_stream_id: Dict[int, int]\n their_stream_id: Dict[int, int]\n stream_queue: DefaultDict[int, List[Event]]\n \"\"\"Queue of streams that we haven't sent yet because we have reached MAX_CONCURRENT_STREAMS\"\"\"\n provisional_max_concurrency: Optional[int] = 10\n \"\"\"A provisional currency limit before we get the server's first settings frame.\"\"\"",
" def __init__(self, context: Context):\n super().__init__(context, context.server)\n # Disable HTTP/2 push for now to keep things simple.\n # don't send here, that is done as part of initiate_connection().\n self.h2_conn.local_settings.enable_push = 0\n # hyper-h2 pitfall: we need to acknowledge here, otherwise its sends out the old settings.\n self.h2_conn.local_settings.acknowledge()\n self.our_stream_id = {}\n self.their_stream_id = {}\n self.stream_queue = collections.defaultdict(list)",
" def _handle_event(self, event: Event) -> CommandGenerator[None]:\n # We can't reuse stream ids from the client because they may arrived reordered here\n # and HTTP/2 forbids opening a stream on a lower id than what was previously sent (see test_stream_concurrency).\n # To mitigate this, we transparently map the outside's stream id to our stream id.\n if isinstance(event, HttpEvent):\n ours = self.our_stream_id.get(event.stream_id, None)\n if ours is None:\n no_free_streams = (\n self.h2_conn.open_outbound_streams >=\n (self.provisional_max_concurrency or self.h2_conn.remote_settings.max_concurrent_streams)\n )\n if no_free_streams:\n self.stream_queue[event.stream_id].append(event)\n return\n ours = self.h2_conn.get_next_available_stream_id()\n self.our_stream_id[event.stream_id] = ours\n self.their_stream_id[ours] = event.stream_id\n event.stream_id = ours",
" for cmd in self._handle_event2(event):\n if isinstance(cmd, ReceiveHttp):\n cmd.event.stream_id = self.their_stream_id[cmd.event.stream_id]\n yield cmd",
" can_resume_queue = (\n self.stream_queue and\n self.h2_conn.open_outbound_streams < (\n self.provisional_max_concurrency or self.h2_conn.remote_settings.max_concurrent_streams\n )\n )\n if can_resume_queue:\n # popitem would be LIFO, but we want FIFO.\n events = self.stream_queue.pop(next(iter(self.stream_queue)))\n for event in events:\n yield from self._handle_event(event)",
" def _handle_event2(self, event: Event) -> CommandGenerator[None]:\n if isinstance(event, RequestHeaders):\n pseudo_headers = [\n (b':method', event.request.data.method),\n (b':scheme', event.request.data.scheme),\n (b':path', event.request.data.path),\n ]\n if event.request.authority:\n pseudo_headers.append((b\":authority\", event.request.data.authority))",
" if event.request.is_http2:\n hdrs = list(event.request.headers.fields)\n if self.context.options.normalize_outbound_headers:\n yield from normalize_h2_headers(hdrs)\n else:\n headers = event.request.headers\n if not event.request.authority and \"host\" in headers:\n headers = headers.copy()\n pseudo_headers.append((b\":authority\", headers.pop(b\"host\")))\n hdrs = normalize_h1_headers(list(headers.fields), True)",
" self.h2_conn.send_headers(\n event.stream_id,\n pseudo_headers + hdrs,\n end_stream=event.end_stream,\n )\n self.streams[event.stream_id] = StreamState.EXPECTING_HEADERS\n yield SendData(self.conn, self.h2_conn.data_to_send())\n else:\n yield from super()._handle_event(event)",
" def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:\n if isinstance(event, h2.events.ResponseReceived):\n if self.streams.get(event.stream_id, None) is not StreamState.EXPECTING_HEADERS:\n yield from self.protocol_error(f\"Received unexpected HTTP/2 response.\")\n return True",
" try:\n status_code, headers = parse_h2_response_headers(event.headers)\n except ValueError as e:\n yield from self.protocol_error(f\"Invalid HTTP/2 response headers: {e}\")\n return True",
" response = http.Response(\n http_version=b\"HTTP/2.0\",\n status_code=status_code,\n reason=b\"\",\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None,\n )\n self.streams[event.stream_id] = StreamState.HEADERS_RECEIVED\n yield ReceiveHttp(ResponseHeaders(event.stream_id, response, bool(event.stream_ended)))\n return False\n elif isinstance(event, h2.events.RequestReceived):\n yield from self.protocol_error(f\"HTTP/2 protocol error: received request from server\")\n return True\n elif isinstance(event, h2.events.RemoteSettingsChanged):\n # We have received at least one settings from now,\n # which means we can rely on the max concurrency in remote_settings\n self.provisional_max_concurrency = None\n return (yield from super().handle_h2_event(event))\n else:\n return (yield from super().handle_h2_event(event))",
"\ndef split_pseudo_headers(h2_headers: Sequence[Tuple[bytes, bytes]]) -> Tuple[Dict[bytes, bytes], http.Headers]:\n pseudo_headers: Dict[bytes, bytes] = {}\n i = 0\n for (header, value) in h2_headers:\n if header.startswith(b\":\"):\n if header in pseudo_headers:\n raise ValueError(f\"Duplicate HTTP/2 pseudo header: {header!r}\")\n pseudo_headers[header] = value\n i += 1\n else:\n # Pseudo-headers must be at the start, we are done here.\n break",
" headers = http.Headers(h2_headers[i:])",
" return pseudo_headers, headers",
"\ndef parse_h2_request_headers(\n h2_headers: Sequence[Tuple[bytes, bytes]]\n) -> Tuple[str, int, bytes, bytes, bytes, bytes, http.Headers]:\n \"\"\"Split HTTP/2 pseudo-headers from the actual headers and parse them.\"\"\"\n pseudo_headers, headers = split_pseudo_headers(h2_headers)",
" try:\n method: bytes = pseudo_headers.pop(b\":method\")\n scheme: bytes = pseudo_headers.pop(b\":scheme\") # this raises for HTTP/2 CONNECT requests\n path: bytes = pseudo_headers.pop(b\":path\")\n authority: bytes = pseudo_headers.pop(b\":authority\", b\"\")\n except KeyError as e:\n raise ValueError(f\"Required pseudo header is missing: {e}\")",
" if pseudo_headers:\n raise ValueError(f\"Unknown pseudo headers: {pseudo_headers}\")",
" if authority:\n host, port = url.parse_authority(authority, check=True)\n if port is None:\n port = 80 if scheme == b'http' else 443\n else:\n host = \"\"\n port = 0",
" return host, port, method, scheme, authority, path, headers",
"\ndef parse_h2_response_headers(h2_headers: Sequence[Tuple[bytes, bytes]]) -> Tuple[int, http.Headers]:\n \"\"\"Split HTTP/2 pseudo-headers from the actual headers and parse them.\"\"\"\n pseudo_headers, headers = split_pseudo_headers(h2_headers)",
" try:\n status_code: int = int(pseudo_headers.pop(b\":status\"))\n except KeyError as e:\n raise ValueError(f\"Required pseudo header is missing: {e}\")",
" if pseudo_headers:\n raise ValueError(f\"Unknown pseudo headers: {pseudo_headers}\")",
" return status_code, headers",
"\n__all__ = [\n \"Http2Client\",\n \"Http2Server\",\n]"
] |
[
1,
1,
1,
1,
1,
1,
0,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import collections\nimport time\nfrom enum import Enum\nfrom typing import ClassVar, DefaultDict, Dict, List, Optional, Sequence, Tuple, Type, Union",
"import h2.config\nimport h2.connection\nimport h2.errors\nimport h2.events\nimport h2.exceptions\nimport h2.settings\nimport h2.stream\nimport h2.utilities",
"from mitmproxy import http, version\nfrom mitmproxy.connection import Connection\nfrom mitmproxy.net.http import status_codes, url\nfrom mitmproxy.utils import human\nfrom . import RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \\\n ResponseEndOfMessage, ResponseHeaders, RequestTrailers, ResponseTrailers, ResponseProtocolError\nfrom ._base import HttpConnection, HttpEvent, ReceiveHttp, format_error\nfrom ._http_h2 import BufferedH2Connection, H2ConnectionLogger\nfrom ...commands import CloseConnection, Log, SendData\nfrom ...context import Context\nfrom ...events import ConnectionClosed, DataReceived, Event, Start\nfrom ...layer import CommandGenerator\nfrom ...utils import expect",
"\nclass StreamState(Enum):\n EXPECTING_HEADERS = 1\n HEADERS_RECEIVED = 2",
"\nCATCH_HYPER_H2_ERRORS = (ValueError, IndexError)",
"\nclass Http2Connection(HttpConnection):\n h2_conf: ClassVar[h2.config.H2Configuration]\n h2_conf_defaults = dict(\n header_encoding=False,\n validate_outbound_headers=False,",
" # validate_inbound_headers is controlled by the validate_inbound_headers option.",
" normalize_inbound_headers=False, # changing this to True is required to pass h2spec\n normalize_outbound_headers=False,\n )\n h2_conn: BufferedH2Connection\n streams: Dict[int, StreamState]\n \"\"\"keep track of all active stream ids to send protocol errors on teardown\"\"\"",
" ReceiveProtocolError: Type[Union[RequestProtocolError, ResponseProtocolError]]\n ReceiveData: Type[Union[RequestData, ResponseData]]\n ReceiveTrailers: Type[Union[RequestTrailers, ResponseTrailers]]\n ReceiveEndOfMessage: Type[Union[RequestEndOfMessage, ResponseEndOfMessage]]",
" def __init__(self, context: Context, conn: Connection):\n super().__init__(context, conn)\n if self.debug:\n self.h2_conf.logger = H2ConnectionLogger(f\"{human.format_address(self.context.client.peername)}: \"\n f\"{self.__class__.__name__}\")",
" self.h2_conf.validate_inbound_headers = self.context.options.validate_inbound_headers",
" self.h2_conn = BufferedH2Connection(self.h2_conf)\n self.streams = {}",
" def is_closed(self, stream_id: int) -> bool:\n \"\"\"Check if a non-idle stream is closed\"\"\"\n stream = self.h2_conn.streams.get(stream_id, None)\n if (\n stream is not None\n and\n stream.state_machine.state is not h2.stream.StreamState.CLOSED\n and\n self.h2_conn.state_machine.state is not h2.connection.ConnectionState.CLOSED\n ):\n return False\n else:\n return True",
" def is_open_for_us(self, stream_id: int) -> bool:\n \"\"\"Check if we can write to a non-idle stream.\"\"\"\n stream = self.h2_conn.streams.get(stream_id, None)\n if (\n stream is not None\n and\n stream.state_machine.state is not h2.stream.StreamState.HALF_CLOSED_LOCAL\n and\n stream.state_machine.state is not h2.stream.StreamState.CLOSED\n and\n self.h2_conn.state_machine.state is not h2.connection.ConnectionState.CLOSED\n ):\n return True\n else:\n return False",
" def _handle_event(self, event: Event) -> CommandGenerator[None]:\n if isinstance(event, Start):\n self.h2_conn.initiate_connection()\n yield SendData(self.conn, self.h2_conn.data_to_send())",
" elif isinstance(event, HttpEvent):\n if isinstance(event, (RequestData, ResponseData)):\n if self.is_open_for_us(event.stream_id):\n self.h2_conn.send_data(event.stream_id, event.data)\n elif isinstance(event, (RequestTrailers, ResponseTrailers)):\n if self.is_open_for_us(event.stream_id):\n trailers = [*event.trailers.fields]\n self.h2_conn.send_headers(event.stream_id, trailers, end_stream=True)\n elif isinstance(event, (RequestEndOfMessage, ResponseEndOfMessage)):\n if self.is_open_for_us(event.stream_id):\n self.h2_conn.end_stream(event.stream_id)\n elif isinstance(event, (RequestProtocolError, ResponseProtocolError)):\n if not self.is_closed(event.stream_id):\n code = {\n status_codes.CLIENT_CLOSED_REQUEST: h2.errors.ErrorCodes.CANCEL,\n }.get(event.code, h2.errors.ErrorCodes.INTERNAL_ERROR)\n stream: h2.stream.H2Stream = self.h2_conn.streams[event.stream_id]\n send_error_message = (\n isinstance(event, ResponseProtocolError)\n and self.is_open_for_us(event.stream_id)\n and not stream.state_machine.headers_sent\n and event.code != status_codes.NO_RESPONSE\n )\n if send_error_message:\n self.h2_conn.send_headers(event.stream_id, [\n (b\":status\", b\"%d\" % event.code),\n (b\"server\", version.MITMPROXY.encode()),\n (b\"content-type\", b\"text/html\"),\n ])\n self.h2_conn.send_data(\n event.stream_id,\n format_error(event.code, event.message),\n end_stream=True\n )\n else:\n self.h2_conn.reset_stream(event.stream_id, code)\n else:\n raise AssertionError(f\"Unexpected event: {event}\")\n data_to_send = self.h2_conn.data_to_send()\n if data_to_send:\n yield SendData(self.conn, data_to_send)",
" elif isinstance(event, DataReceived):\n try:\n try:\n events = self.h2_conn.receive_data(event.data)\n except CATCH_HYPER_H2_ERRORS as e: # pragma: no cover\n # this should never raise a ValueError, but we triggered one while fuzzing:\n # https://github.com/python-hyper/hyper-h2/issues/1231\n # this stays here as defense-in-depth.\n raise h2.exceptions.ProtocolError(f\"uncaught hyper-h2 error: {e}\") from e\n except h2.exceptions.ProtocolError as e:\n events = [e]",
" for h2_event in events:\n if self.debug:\n yield Log(f\"{self.debug}[h2] {h2_event}\", \"debug\")\n if (yield from self.handle_h2_event(h2_event)):\n if self.debug:\n yield Log(f\"{self.debug}[h2] done\", \"debug\")\n return",
" data_to_send = self.h2_conn.data_to_send()\n if data_to_send:\n yield SendData(self.conn, data_to_send)",
" elif isinstance(event, ConnectionClosed):\n yield from self.close_connection(\"peer closed connection\")\n else:\n raise AssertionError(f\"Unexpected event: {event!r}\")",
" def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:\n \"\"\"returns true if further processing should be stopped.\"\"\"\n if isinstance(event, h2.events.DataReceived):\n state = self.streams.get(event.stream_id, None)\n if state is StreamState.HEADERS_RECEIVED:\n yield ReceiveHttp(self.ReceiveData(event.stream_id, event.data))\n elif state is StreamState.EXPECTING_HEADERS:\n yield from self.protocol_error(f\"Received HTTP/2 data frame, expected headers.\")\n return True\n self.h2_conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)\n elif isinstance(event, h2.events.TrailersReceived):\n trailers = http.Headers(event.headers)\n yield ReceiveHttp(self.ReceiveTrailers(event.stream_id, trailers))\n elif isinstance(event, h2.events.StreamEnded):\n state = self.streams.get(event.stream_id, None)\n if state is StreamState.HEADERS_RECEIVED:\n yield ReceiveHttp(self.ReceiveEndOfMessage(event.stream_id))\n elif state is StreamState.EXPECTING_HEADERS:\n raise AssertionError(\"unreachable\")\n if self.is_closed(event.stream_id):\n self.streams.pop(event.stream_id, None)\n elif isinstance(event, h2.events.StreamReset):\n if event.stream_id in self.streams:\n try:\n err_str = h2.errors.ErrorCodes(event.error_code).name\n except ValueError:\n err_str = str(event.error_code)\n err_code = {\n h2.errors.ErrorCodes.CANCEL: status_codes.CLIENT_CLOSED_REQUEST,\n }.get(event.error_code, self.ReceiveProtocolError.code)\n yield ReceiveHttp(self.ReceiveProtocolError(event.stream_id, f\"stream reset by client ({err_str})\",\n code=err_code))\n self.streams.pop(event.stream_id)\n else:\n pass # We don't track priority frames which could be followed by a stream reset here.\n elif isinstance(event, h2.exceptions.ProtocolError):\n yield from self.protocol_error(f\"HTTP/2 protocol error: {event}\")\n return True\n elif isinstance(event, h2.events.ConnectionTerminated):\n yield from self.close_connection(f\"HTTP/2 connection closed: {event!r}\")\n return True\n # The implementation above isn't really ideal, we should probably only terminate streams > last_stream_id?\n # We currently lack a mechanism to signal that connections are still active but cannot be reused.\n # for stream_id in self.streams:\n # if stream_id > event.last_stream_id:\n # yield ReceiveHttp(self.ReceiveProtocolError(stream_id, f\"HTTP/2 connection closed: {event!r}\"))\n # self.streams.pop(stream_id)\n elif isinstance(event, h2.events.RemoteSettingsChanged):\n pass\n elif isinstance(event, h2.events.SettingsAcknowledged):\n pass\n elif isinstance(event, h2.events.PriorityUpdated):\n pass\n elif isinstance(event, h2.events.PingReceived):\n pass\n elif isinstance(event, h2.events.PingAckReceived):\n pass\n elif isinstance(event, h2.events.PushedStreamReceived):\n yield Log(\"Received HTTP/2 push promise, even though we signalled no support.\", \"error\")\n elif isinstance(event, h2.events.UnknownFrameReceived):\n # https://http2.github.io/http2-spec/#rfc.section.4.1\n # Implementations MUST ignore and discard any frame that has a type that is unknown.\n yield Log(f\"Ignoring unknown HTTP/2 frame type: {event.frame.type}\")\n else:\n raise AssertionError(f\"Unexpected event: {event!r}\")\n return False",
" def protocol_error(\n self,\n message: str,\n error_code: int = h2.errors.ErrorCodes.PROTOCOL_ERROR,\n ) -> CommandGenerator[None]:\n yield Log(f\"{human.format_address(self.conn.peername)}: {message}\")\n self.h2_conn.close_connection(error_code, message.encode())\n yield SendData(self.conn, self.h2_conn.data_to_send())\n yield from self.close_connection(message)",
" def close_connection(self, msg: str) -> CommandGenerator[None]:\n yield CloseConnection(self.conn)\n for stream_id in self.streams:\n yield ReceiveHttp(self.ReceiveProtocolError(stream_id, msg))\n self.streams.clear()\n self._handle_event = self.done # type: ignore",
" @expect(DataReceived, HttpEvent, ConnectionClosed)\n def done(self, _) -> CommandGenerator[None]:\n yield from ()",
"\ndef normalize_h1_headers(headers: List[Tuple[bytes, bytes]], is_client: bool) -> List[Tuple[bytes, bytes]]:\n # HTTP/1 servers commonly send capitalized headers (Content-Length vs content-length),\n # which isn't valid HTTP/2. As such we normalize.\n headers = h2.utilities.normalize_outbound_headers(\n headers,\n h2.utilities.HeaderValidationFlags(is_client, False, not is_client, False)\n )\n # make sure that this is not just an iterator but an iterable,\n # otherwise hyper-h2 will silently drop headers.\n headers = list(headers)\n return headers",
"\ndef normalize_h2_headers(headers: List[Tuple[bytes, bytes]]) -> CommandGenerator[None]:\n for i in range(len(headers)):\n if not headers[i][0].islower():\n yield Log(f\"Lowercased {repr(headers[i][0]).lstrip('b')} header as uppercase is not allowed with HTTP/2.\")\n headers[i] = (headers[i][0].lower(), headers[i][1])",
"\nclass Http2Server(Http2Connection):\n h2_conf = h2.config.H2Configuration(\n **Http2Connection.h2_conf_defaults,\n client_side=False,\n )",
" ReceiveProtocolError = RequestProtocolError\n ReceiveData = RequestData\n ReceiveTrailers = RequestTrailers\n ReceiveEndOfMessage = RequestEndOfMessage",
" def __init__(self, context: Context):\n super().__init__(context, context.client)",
" def _handle_event(self, event: Event) -> CommandGenerator[None]:\n if isinstance(event, ResponseHeaders):\n if self.is_open_for_us(event.stream_id):\n headers = [\n (b\":status\", b\"%d\" % event.response.status_code),\n *event.response.headers.fields\n ]\n if event.response.is_http2:\n if self.context.options.normalize_outbound_headers:\n yield from normalize_h2_headers(headers)\n else:\n headers = normalize_h1_headers(headers, False)",
" self.h2_conn.send_headers(\n event.stream_id,\n headers,\n end_stream=event.end_stream,\n )\n yield SendData(self.conn, self.h2_conn.data_to_send())\n else:\n yield from super()._handle_event(event)",
" def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:\n if isinstance(event, h2.events.RequestReceived):\n try:\n host, port, method, scheme, authority, path, headers = parse_h2_request_headers(event.headers)\n except ValueError as e:\n yield from self.protocol_error(f\"Invalid HTTP/2 request headers: {e}\")\n return True\n request = http.Request(\n host=host,\n port=port,\n method=method,\n scheme=scheme,\n authority=authority,\n path=path,\n http_version=b\"HTTP/2.0\",\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None,\n )\n self.streams[event.stream_id] = StreamState.HEADERS_RECEIVED\n yield ReceiveHttp(RequestHeaders(event.stream_id, request, end_stream=bool(event.stream_ended)))\n return False\n else:\n return (yield from super().handle_h2_event(event))",
"\nclass Http2Client(Http2Connection):\n h2_conf = h2.config.H2Configuration(\n **Http2Connection.h2_conf_defaults,\n client_side=True,\n )",
" ReceiveProtocolError = ResponseProtocolError\n ReceiveData = ResponseData\n ReceiveTrailers = ResponseTrailers\n ReceiveEndOfMessage = ResponseEndOfMessage",
" our_stream_id: Dict[int, int]\n their_stream_id: Dict[int, int]\n stream_queue: DefaultDict[int, List[Event]]\n \"\"\"Queue of streams that we haven't sent yet because we have reached MAX_CONCURRENT_STREAMS\"\"\"\n provisional_max_concurrency: Optional[int] = 10\n \"\"\"A provisional currency limit before we get the server's first settings frame.\"\"\"",
" def __init__(self, context: Context):\n super().__init__(context, context.server)\n # Disable HTTP/2 push for now to keep things simple.\n # don't send here, that is done as part of initiate_connection().\n self.h2_conn.local_settings.enable_push = 0\n # hyper-h2 pitfall: we need to acknowledge here, otherwise its sends out the old settings.\n self.h2_conn.local_settings.acknowledge()\n self.our_stream_id = {}\n self.their_stream_id = {}\n self.stream_queue = collections.defaultdict(list)",
" def _handle_event(self, event: Event) -> CommandGenerator[None]:\n # We can't reuse stream ids from the client because they may arrived reordered here\n # and HTTP/2 forbids opening a stream on a lower id than what was previously sent (see test_stream_concurrency).\n # To mitigate this, we transparently map the outside's stream id to our stream id.\n if isinstance(event, HttpEvent):\n ours = self.our_stream_id.get(event.stream_id, None)\n if ours is None:\n no_free_streams = (\n self.h2_conn.open_outbound_streams >=\n (self.provisional_max_concurrency or self.h2_conn.remote_settings.max_concurrent_streams)\n )\n if no_free_streams:\n self.stream_queue[event.stream_id].append(event)\n return\n ours = self.h2_conn.get_next_available_stream_id()\n self.our_stream_id[event.stream_id] = ours\n self.their_stream_id[ours] = event.stream_id\n event.stream_id = ours",
" for cmd in self._handle_event2(event):\n if isinstance(cmd, ReceiveHttp):\n cmd.event.stream_id = self.their_stream_id[cmd.event.stream_id]\n yield cmd",
" can_resume_queue = (\n self.stream_queue and\n self.h2_conn.open_outbound_streams < (\n self.provisional_max_concurrency or self.h2_conn.remote_settings.max_concurrent_streams\n )\n )\n if can_resume_queue:\n # popitem would be LIFO, but we want FIFO.\n events = self.stream_queue.pop(next(iter(self.stream_queue)))\n for event in events:\n yield from self._handle_event(event)",
" def _handle_event2(self, event: Event) -> CommandGenerator[None]:\n if isinstance(event, RequestHeaders):\n pseudo_headers = [\n (b':method', event.request.data.method),\n (b':scheme', event.request.data.scheme),\n (b':path', event.request.data.path),\n ]\n if event.request.authority:\n pseudo_headers.append((b\":authority\", event.request.data.authority))",
" if event.request.is_http2:\n hdrs = list(event.request.headers.fields)\n if self.context.options.normalize_outbound_headers:\n yield from normalize_h2_headers(hdrs)\n else:\n headers = event.request.headers\n if not event.request.authority and \"host\" in headers:\n headers = headers.copy()\n pseudo_headers.append((b\":authority\", headers.pop(b\"host\")))\n hdrs = normalize_h1_headers(list(headers.fields), True)",
" self.h2_conn.send_headers(\n event.stream_id,\n pseudo_headers + hdrs,\n end_stream=event.end_stream,\n )\n self.streams[event.stream_id] = StreamState.EXPECTING_HEADERS\n yield SendData(self.conn, self.h2_conn.data_to_send())\n else:\n yield from super()._handle_event(event)",
" def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:\n if isinstance(event, h2.events.ResponseReceived):\n if self.streams.get(event.stream_id, None) is not StreamState.EXPECTING_HEADERS:\n yield from self.protocol_error(f\"Received unexpected HTTP/2 response.\")\n return True",
" try:\n status_code, headers = parse_h2_response_headers(event.headers)\n except ValueError as e:\n yield from self.protocol_error(f\"Invalid HTTP/2 response headers: {e}\")\n return True",
" response = http.Response(\n http_version=b\"HTTP/2.0\",\n status_code=status_code,\n reason=b\"\",\n headers=headers,\n content=None,\n trailers=None,\n timestamp_start=time.time(),\n timestamp_end=None,\n )\n self.streams[event.stream_id] = StreamState.HEADERS_RECEIVED\n yield ReceiveHttp(ResponseHeaders(event.stream_id, response, bool(event.stream_ended)))\n return False\n elif isinstance(event, h2.events.RequestReceived):\n yield from self.protocol_error(f\"HTTP/2 protocol error: received request from server\")\n return True\n elif isinstance(event, h2.events.RemoteSettingsChanged):\n # We have received at least one settings from now,\n # which means we can rely on the max concurrency in remote_settings\n self.provisional_max_concurrency = None\n return (yield from super().handle_h2_event(event))\n else:\n return (yield from super().handle_h2_event(event))",
"\ndef split_pseudo_headers(h2_headers: Sequence[Tuple[bytes, bytes]]) -> Tuple[Dict[bytes, bytes], http.Headers]:\n pseudo_headers: Dict[bytes, bytes] = {}\n i = 0\n for (header, value) in h2_headers:\n if header.startswith(b\":\"):\n if header in pseudo_headers:\n raise ValueError(f\"Duplicate HTTP/2 pseudo header: {header!r}\")\n pseudo_headers[header] = value\n i += 1\n else:\n # Pseudo-headers must be at the start, we are done here.\n break",
" headers = http.Headers(h2_headers[i:])",
" return pseudo_headers, headers",
"\ndef parse_h2_request_headers(\n h2_headers: Sequence[Tuple[bytes, bytes]]\n) -> Tuple[str, int, bytes, bytes, bytes, bytes, http.Headers]:\n \"\"\"Split HTTP/2 pseudo-headers from the actual headers and parse them.\"\"\"\n pseudo_headers, headers = split_pseudo_headers(h2_headers)",
" try:\n method: bytes = pseudo_headers.pop(b\":method\")\n scheme: bytes = pseudo_headers.pop(b\":scheme\") # this raises for HTTP/2 CONNECT requests\n path: bytes = pseudo_headers.pop(b\":path\")\n authority: bytes = pseudo_headers.pop(b\":authority\", b\"\")\n except KeyError as e:\n raise ValueError(f\"Required pseudo header is missing: {e}\")",
" if pseudo_headers:\n raise ValueError(f\"Unknown pseudo headers: {pseudo_headers}\")",
" if authority:\n host, port = url.parse_authority(authority, check=True)\n if port is None:\n port = 80 if scheme == b'http' else 443\n else:\n host = \"\"\n port = 0",
" return host, port, method, scheme, authority, path, headers",
"\ndef parse_h2_response_headers(h2_headers: Sequence[Tuple[bytes, bytes]]) -> Tuple[int, http.Headers]:\n \"\"\"Split HTTP/2 pseudo-headers from the actual headers and parse them.\"\"\"\n pseudo_headers, headers = split_pseudo_headers(h2_headers)",
" try:\n status_code: int = int(pseudo_headers.pop(b\":status\"))\n except KeyError as e:\n raise ValueError(f\"Required pseudo header is missing: {e}\")",
" if pseudo_headers:\n raise ValueError(f\"Unknown pseudo headers: {pseudo_headers}\")",
" return status_code, headers",
"\n__all__ = [\n \"Http2Client\",\n \"Http2Server\",\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import pytest",
"from mitmproxy.http import Headers\nfrom mitmproxy.net.http.http1.read import (\n read_request_head,\n read_response_head, connection_close, expected_http_body_size,",
" _read_request_line, _read_response_line, _read_headers, get_header_tokens",
")\nfrom mitmproxy.test.tutils import treq, tresp",
"\ndef test_get_header_tokens():\n headers = Headers()\n assert get_header_tokens(headers, \"foo\") == []\n headers[\"foo\"] = \"bar\"\n assert get_header_tokens(headers, \"foo\") == [\"bar\"]\n headers[\"foo\"] = \"bar, voing\"\n assert get_header_tokens(headers, \"foo\") == [\"bar\", \"voing\"]\n headers.set_all(\"foo\", [\"bar, voing\", \"oink\"])\n assert get_header_tokens(headers, \"foo\") == [\"bar\", \"voing\", \"oink\"]",
"\ndef test_connection_close():\n headers = Headers()\n assert connection_close(b\"HTTP/1.0\", headers)\n assert not connection_close(b\"HTTP/1.1\", headers)\n assert not connection_close(b\"HTTP/2.0\", headers)",
" headers[\"connection\"] = \"keep-alive\"\n assert not connection_close(b\"HTTP/1.1\", headers)",
" headers[\"connection\"] = \"close\"\n assert connection_close(b\"HTTP/1.1\", headers)",
" headers[\"connection\"] = \"foobar\"\n assert connection_close(b\"HTTP/1.0\", headers)\n assert not connection_close(b\"HTTP/1.1\", headers)",
"\ndef test_read_request_head():\n rfile = [\n b\"GET / HTTP/1.1\\r\\n\",\n b\"Content-Length: 4\\r\\n\",\n ]\n r = read_request_head(rfile)\n assert r.method == \"GET\"\n assert r.headers[\"Content-Length\"] == \"4\"\n assert r.content is None",
"\ndef test_read_response_head():\n rfile = [\n b\"HTTP/1.1 418 I'm a teapot\\r\\n\",\n b\"Content-Length: 4\\r\\n\",\n ]\n r = read_response_head(rfile)\n assert r.status_code == 418\n assert r.headers[\"Content-Length\"] == \"4\"\n assert r.content is None",
"",
"",
"def test_expected_http_body_size():\n # Expect: 100-continue\n assert expected_http_body_size(\n treq(headers=Headers(expect=\"100-continue\", content_length=\"42\")),\n ) == 42",
" # http://tools.ietf.org/html/rfc7230#section-3.3\n assert expected_http_body_size(\n treq(method=b\"HEAD\"),\n tresp(headers=Headers(content_length=\"42\"))\n ) == 0\n assert expected_http_body_size(\n treq(method=b\"CONNECT\", headers=Headers()),\n None,\n ) == 0\n assert expected_http_body_size(\n treq(method=b\"CONNECT\"),\n tresp()\n ) == 0\n for code in (100, 204, 304):\n assert expected_http_body_size(\n treq(),\n tresp(status_code=code)\n ) == 0",
" # chunked\n assert expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chunked\")),\n ) is None\n assert expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"gzip,\\tchunked\")),\n ) is None",
" # both content-length and chunked (possible request smuggling)\n with pytest.raises(ValueError, match=\"Received both a Transfer-Encoding and a Content-Length header\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chunked\", content_length=\"42\")),\n )",
" with pytest.raises(ValueError, match=\"Invalid transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chun\\u212Aed\")), # \"chunKed\".lower() == \"chunked\"\n )\n with pytest.raises(ValueError, match=\"Unknown transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chun ked\")), # \"chunKed\".lower() == \"chunked\"\n )\n with pytest.raises(ValueError, match=\"Unknown transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"qux\")),\n )\n # transfer-encoding: gzip\n with pytest.raises(ValueError, match=\"Invalid request transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"gzip\")),\n )\n assert expected_http_body_size(\n treq(),\n tresp(headers=Headers(transfer_encoding=\"gzip\")),\n ) == -1",
" # explicit length\n for val in (b\"foo\", b\"-7\"):\n with pytest.raises(ValueError):\n expected_http_body_size(\n treq(headers=Headers(content_length=val))\n )\n assert expected_http_body_size(\n treq(headers=Headers(content_length=\"42\"))\n ) == 42\n # multiple content-length headers with same value\n assert expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'42'), (b'content-length', b'42')]))\n ) == 42\n # multiple content-length headers with conflicting value\n with pytest.raises(ValueError, match=\"Conflicting Content-Length headers\"):\n expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'42'), (b'content-length', b'45')]))\n )",
" # non-int content-length\n with pytest.raises(ValueError, match=\"Invalid Content-Length header\"):\n expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'NaN')]))\n )\n # negative content-length\n with pytest.raises(ValueError, match=\"Negative Content-Length header\"):\n expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'-1')]))\n )",
" # no length\n assert expected_http_body_size(\n treq(headers=Headers())\n ) == 0\n assert expected_http_body_size(\n treq(headers=Headers()), tresp(headers=Headers())\n ) == -1",
"\ndef test_read_request_line():\n def t(b):\n return _read_request_line(b)",
" assert (t(b\"GET / HTTP/1.1\") ==\n (\"\", 0, b\"GET\", b\"\", b\"\", b\"/\", b\"HTTP/1.1\"))\n assert (t(b\"OPTIONS * HTTP/1.1\") ==\n (\"\", 0, b\"OPTIONS\", b\"\", b\"\", b\"*\", b\"HTTP/1.1\"))\n assert (t(b\"CONNECT foo:42 HTTP/1.1\") ==\n (\"foo\", 42, b\"CONNECT\", b\"\", b\"foo:42\", b\"\", b\"HTTP/1.1\"))\n assert (t(b\"GET http://foo:42/bar HTTP/1.1\") ==\n (\"foo\", 42, b\"GET\", b\"http\", b\"foo:42\", b\"/bar\", b\"HTTP/1.1\"))\n assert (t(b\"GET http://foo:42 HTTP/1.1\") ==\n (\"foo\", 42, b\"GET\", b\"http\", b\"foo:42\", b\"/\", b\"HTTP/1.1\"))",
" with pytest.raises(ValueError):\n t(b\"GET / WTF/1.1\")\n with pytest.raises(ValueError):\n t(b\"CONNECT example.com HTTP/1.1\") # port missing\n with pytest.raises(ValueError):\n t(b\"GET ws://example.com/ HTTP/1.1\") # port missing\n with pytest.raises(ValueError):\n t(b\"this is not http\")\n with pytest.raises(ValueError):\n t(b\"\")",
"\ndef test_read_response_line():\n def t(b):\n return _read_response_line(b)",
" assert t(b\"HTTP/1.1 200 OK\") == (b\"HTTP/1.1\", 200, b\"OK\")\n assert t(b\"HTTP/1.1 200\") == (b\"HTTP/1.1\", 200, b\"\")",
" # https://github.com/mitmproxy/mitmproxy/issues/784\n assert t(b\"HTTP/1.1 200 Non-Autoris\\xc3\\xa9\") == (b\"HTTP/1.1\", 200, b\"Non-Autoris\\xc3\\xa9\")",
" with pytest.raises(ValueError):\n assert t(b\"HTTP/1.1\")",
" with pytest.raises(ValueError):\n t(b\"HTTP/1.1 OK OK\")\n with pytest.raises(ValueError):\n t(b\"WTF/1.1 200 OK\")\n with pytest.raises(ValueError):\n t(b\"\")",
"\nclass TestReadHeaders:\n @staticmethod\n def _read(data):\n return _read_headers(data.splitlines(keepends=True))",
" def test_read_simple(self):\n data = (\n b\"Header: one\\r\\n\"\n b\"Header2: two\\r\\n\"\n )\n headers = self._read(data)\n assert headers.fields == ((b\"Header\", b\"one\"), (b\"Header2\", b\"two\"))",
" def test_read_multi(self):\n data = (\n b\"Header: one\\r\\n\"\n b\"Header: two\\r\\n\"\n )\n headers = self._read(data)\n assert headers.fields == ((b\"Header\", b\"one\"), (b\"Header\", b\"two\"))",
" def test_read_continued(self):\n data = (\n b\"Header: one\\r\\n\"\n b\"\\ttwo\\r\\n\"\n b\"Header2: three\\r\\n\"\n )\n headers = self._read(data)\n assert headers.fields == ((b\"Header\", b\"one\\r\\n two\"), (b\"Header2\", b\"three\"))",
" def test_read_continued_err(self):\n data = b\"\\tfoo: bar\\r\\n\"\n with pytest.raises(ValueError):\n self._read(data)",
" def test_read_err(self):\n data = b\"foo\"\n with pytest.raises(ValueError):\n self._read(data)",
" def test_read_empty_name(self):\n data = b\":foo\"\n with pytest.raises(ValueError):\n self._read(data)",
" def test_read_empty_value(self):\n data = b\"bar:\"\n headers = self._read(data)\n assert headers.fields == ((b\"bar\", b\"\"),)"
] |
[
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
0,
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import pytest",
"from mitmproxy.http import Headers\nfrom mitmproxy.net.http.http1.read import (\n read_request_head,\n read_response_head, connection_close, expected_http_body_size,",
" _read_request_line, _read_response_line, _read_headers, get_header_tokens, validate_headers",
")\nfrom mitmproxy.test.tutils import treq, tresp",
"\ndef test_get_header_tokens():\n headers = Headers()\n assert get_header_tokens(headers, \"foo\") == []\n headers[\"foo\"] = \"bar\"\n assert get_header_tokens(headers, \"foo\") == [\"bar\"]\n headers[\"foo\"] = \"bar, voing\"\n assert get_header_tokens(headers, \"foo\") == [\"bar\", \"voing\"]\n headers.set_all(\"foo\", [\"bar, voing\", \"oink\"])\n assert get_header_tokens(headers, \"foo\") == [\"bar\", \"voing\", \"oink\"]",
"\ndef test_connection_close():\n headers = Headers()\n assert connection_close(b\"HTTP/1.0\", headers)\n assert not connection_close(b\"HTTP/1.1\", headers)\n assert not connection_close(b\"HTTP/2.0\", headers)",
" headers[\"connection\"] = \"keep-alive\"\n assert not connection_close(b\"HTTP/1.1\", headers)",
" headers[\"connection\"] = \"close\"\n assert connection_close(b\"HTTP/1.1\", headers)",
" headers[\"connection\"] = \"foobar\"\n assert connection_close(b\"HTTP/1.0\", headers)\n assert not connection_close(b\"HTTP/1.1\", headers)",
"\ndef test_read_request_head():\n rfile = [\n b\"GET / HTTP/1.1\\r\\n\",\n b\"Content-Length: 4\\r\\n\",\n ]\n r = read_request_head(rfile)\n assert r.method == \"GET\"\n assert r.headers[\"Content-Length\"] == \"4\"\n assert r.content is None",
"\ndef test_read_response_head():\n rfile = [\n b\"HTTP/1.1 418 I'm a teapot\\r\\n\",\n b\"Content-Length: 4\\r\\n\",\n ]\n r = read_response_head(rfile)\n assert r.status_code == 418\n assert r.headers[\"Content-Length\"] == \"4\"\n assert r.content is None",
"",
"def test_validate_headers():\n # both content-length and chunked (possible request smuggling)\n with pytest.raises(ValueError, match=\"Received both a Transfer-Encoding and a Content-Length header\"):\n validate_headers(\n Headers(transfer_encoding=\"chunked\", content_length=\"42\"),\n )",
" with pytest.raises(ValueError, match=\"Received an invalid header name\"):\n validate_headers(\n Headers([(b\"content-length \", b\"42\")]),\n )",
"",
"def test_expected_http_body_size():\n # Expect: 100-continue\n assert expected_http_body_size(\n treq(headers=Headers(expect=\"100-continue\", content_length=\"42\")),\n ) == 42",
" # http://tools.ietf.org/html/rfc7230#section-3.3\n assert expected_http_body_size(\n treq(method=b\"HEAD\"),\n tresp(headers=Headers(content_length=\"42\"))\n ) == 0\n assert expected_http_body_size(\n treq(method=b\"CONNECT\", headers=Headers()),\n None,\n ) == 0\n assert expected_http_body_size(\n treq(method=b\"CONNECT\"),\n tresp()\n ) == 0\n for code in (100, 204, 304):\n assert expected_http_body_size(\n treq(),\n tresp(status_code=code)\n ) == 0",
" # chunked\n assert expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chunked\")),\n ) is None\n assert expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"gzip,\\tchunked\")),\n ) is None",
"",
" with pytest.raises(ValueError, match=\"Invalid transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chun\\u212Aed\")), # \"chunKed\".lower() == \"chunked\"\n )\n with pytest.raises(ValueError, match=\"Unknown transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"chun ked\")), # \"chunKed\".lower() == \"chunked\"\n )\n with pytest.raises(ValueError, match=\"Unknown transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"qux\")),\n )\n # transfer-encoding: gzip\n with pytest.raises(ValueError, match=\"Invalid request transfer encoding\"):\n expected_http_body_size(\n treq(headers=Headers(transfer_encoding=\"gzip\")),\n )\n assert expected_http_body_size(\n treq(),\n tresp(headers=Headers(transfer_encoding=\"gzip\")),\n ) == -1",
" # explicit length\n for val in (b\"foo\", b\"-7\"):\n with pytest.raises(ValueError):\n expected_http_body_size(\n treq(headers=Headers(content_length=val))\n )\n assert expected_http_body_size(\n treq(headers=Headers(content_length=\"42\"))\n ) == 42\n # multiple content-length headers with same value\n assert expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'42'), (b'content-length', b'42')]))\n ) == 42\n # multiple content-length headers with conflicting value\n with pytest.raises(ValueError, match=\"Conflicting Content-Length headers\"):\n expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'42'), (b'content-length', b'45')]))\n )",
" # non-int content-length\n with pytest.raises(ValueError, match=\"Invalid Content-Length header\"):\n expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'NaN')]))\n )\n # negative content-length\n with pytest.raises(ValueError, match=\"Negative Content-Length header\"):\n expected_http_body_size(\n treq(headers=Headers([(b'content-length', b'-1')]))\n )",
" # no length\n assert expected_http_body_size(\n treq(headers=Headers())\n ) == 0\n assert expected_http_body_size(\n treq(headers=Headers()), tresp(headers=Headers())\n ) == -1",
"\ndef test_read_request_line():\n def t(b):\n return _read_request_line(b)",
" assert (t(b\"GET / HTTP/1.1\") ==\n (\"\", 0, b\"GET\", b\"\", b\"\", b\"/\", b\"HTTP/1.1\"))\n assert (t(b\"OPTIONS * HTTP/1.1\") ==\n (\"\", 0, b\"OPTIONS\", b\"\", b\"\", b\"*\", b\"HTTP/1.1\"))\n assert (t(b\"CONNECT foo:42 HTTP/1.1\") ==\n (\"foo\", 42, b\"CONNECT\", b\"\", b\"foo:42\", b\"\", b\"HTTP/1.1\"))\n assert (t(b\"GET http://foo:42/bar HTTP/1.1\") ==\n (\"foo\", 42, b\"GET\", b\"http\", b\"foo:42\", b\"/bar\", b\"HTTP/1.1\"))\n assert (t(b\"GET http://foo:42 HTTP/1.1\") ==\n (\"foo\", 42, b\"GET\", b\"http\", b\"foo:42\", b\"/\", b\"HTTP/1.1\"))",
" with pytest.raises(ValueError):\n t(b\"GET / WTF/1.1\")\n with pytest.raises(ValueError):\n t(b\"CONNECT example.com HTTP/1.1\") # port missing\n with pytest.raises(ValueError):\n t(b\"GET ws://example.com/ HTTP/1.1\") # port missing\n with pytest.raises(ValueError):\n t(b\"this is not http\")\n with pytest.raises(ValueError):\n t(b\"\")",
"\ndef test_read_response_line():\n def t(b):\n return _read_response_line(b)",
" assert t(b\"HTTP/1.1 200 OK\") == (b\"HTTP/1.1\", 200, b\"OK\")\n assert t(b\"HTTP/1.1 200\") == (b\"HTTP/1.1\", 200, b\"\")",
" # https://github.com/mitmproxy/mitmproxy/issues/784\n assert t(b\"HTTP/1.1 200 Non-Autoris\\xc3\\xa9\") == (b\"HTTP/1.1\", 200, b\"Non-Autoris\\xc3\\xa9\")",
" with pytest.raises(ValueError):\n assert t(b\"HTTP/1.1\")",
" with pytest.raises(ValueError):\n t(b\"HTTP/1.1 OK OK\")\n with pytest.raises(ValueError):\n t(b\"WTF/1.1 200 OK\")\n with pytest.raises(ValueError):\n t(b\"\")",
"\nclass TestReadHeaders:\n @staticmethod\n def _read(data):\n return _read_headers(data.splitlines(keepends=True))",
" def test_read_simple(self):\n data = (\n b\"Header: one\\r\\n\"\n b\"Header2: two\\r\\n\"\n )\n headers = self._read(data)\n assert headers.fields == ((b\"Header\", b\"one\"), (b\"Header2\", b\"two\"))",
" def test_read_multi(self):\n data = (\n b\"Header: one\\r\\n\"\n b\"Header: two\\r\\n\"\n )\n headers = self._read(data)\n assert headers.fields == ((b\"Header\", b\"one\"), (b\"Header\", b\"two\"))",
" def test_read_continued(self):\n data = (\n b\"Header: one\\r\\n\"\n b\"\\ttwo\\r\\n\"\n b\"Header2: three\\r\\n\"\n )\n headers = self._read(data)\n assert headers.fields == ((b\"Header\", b\"one\\r\\n two\"), (b\"Header2\", b\"three\"))",
" def test_read_continued_err(self):\n data = b\"\\tfoo: bar\\r\\n\"\n with pytest.raises(ValueError):\n self._read(data)",
" def test_read_err(self):\n data = b\"foo\"\n with pytest.raises(ValueError):\n self._read(data)",
" def test_read_empty_name(self):\n data = b\":foo\"\n with pytest.raises(ValueError):\n self._read(data)",
" def test_read_empty_value(self):\n data = b\"bar:\"\n headers = self._read(data)\n assert headers.fields == ((b\"bar\", b\"\"),)"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import pytest",
"from mitmproxy.connection import ConnectionState, Server\nfrom mitmproxy.flow import Error\nfrom mitmproxy.http import HTTPFlow, Response\nfrom mitmproxy.net.server_spec import ServerSpec\nfrom mitmproxy.proxy import layer\nfrom mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData\nfrom mitmproxy.proxy.events import ConnectionClosed, DataReceived\nfrom mitmproxy.proxy.layers import TCPLayer, http, tls\nfrom mitmproxy.proxy.layers.http import HTTPMode\nfrom mitmproxy.proxy.layers.tcp import TcpMessageInjected, TcpStartHook\nfrom mitmproxy.proxy.layers.websocket import WebsocketStartHook\nfrom mitmproxy.tcp import TCPFlow, TCPMessage\nfrom test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply, reply_next_layer",
"\ndef test_http_proxy(tctx):\n \"\"\"Test a simple HTTP GET / request\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"GET http://example.com/foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n >> DataReceived(server, b\"!\")\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")\n )\n assert server().address == (\"example.com\", 80)",
"\n@pytest.mark.parametrize(\"strategy\", [\"lazy\", \"eager\"])\ndef test_https_proxy(strategy, tctx):\n \"\"\"Test a CONNECT request, followed by a HTTP GET /\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n tctx.options.connection_strategy = strategy",
" (playbook\n >> DataReceived(tctx.client, b\"CONNECT example.proxy:80 HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpConnectHook(Placeholder())\n >> reply())\n if strategy == \"eager\":\n (playbook\n << OpenConnection(server)\n >> reply(None))\n (playbook\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply())\n if strategy == \"lazy\":\n (playbook\n << OpenConnection(server)\n >> reply(None))\n (playbook\n << SendData(server, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\"))\n assert playbook",
"\n@pytest.mark.parametrize(\"https_client\", [False, True])\n@pytest.mark.parametrize(\"https_server\", [False, True])\n@pytest.mark.parametrize(\"strategy\", [\"lazy\", \"eager\"])\ndef test_redirect(strategy, https_server, https_client, tctx, monkeypatch):\n \"\"\"Test redirects between http:// and https:// in regular proxy mode.\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n tctx.options.connection_strategy = strategy\n p = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)",
" if https_server:\n monkeypatch.setattr(tls, \"ServerTLSLayer\", tls.MockTLSLayer)",
" def redirect(flow: HTTPFlow):\n if https_server:\n flow.request.url = \"https://redirected.site/\"\n else:\n flow.request.url = \"http://redirected.site/\"",
" if https_client:\n p >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\")\n if strategy == \"eager\":\n p << OpenConnection(Placeholder())\n p >> reply(None)\n p << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n p >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n p << layer.NextLayerHook(Placeholder())\n p >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n else:\n p >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n p << http.HttpRequestHook(flow)\n p >> reply(side_effect=redirect)\n p << OpenConnection(server)\n p >> reply(None)\n p << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: redirected.site\\r\\n\\r\\n\")\n p >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")\n p << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")",
" assert p\n if https_server:\n assert server().address == (\"redirected.site\", 443)\n else:\n assert server().address == (\"redirected.site\", 80)",
"\ndef test_multiple_server_connections(tctx):\n \"\"\"Test multiple requests being rewritten to different targets.\"\"\"\n server1 = Placeholder(Server)\n server2 = Placeholder(Server)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)",
" def redirect(to: str):\n def side_effect(flow: HTTPFlow):\n flow.request.url = to",
" return side_effect",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHook(Placeholder())\n >> reply(side_effect=redirect(\"http://one.redirect/\"))\n << OpenConnection(server1)\n >> reply(None)\n << SendData(server1, b\"GET / HTTP/1.1\\r\\nHost: one.redirect\\r\\n\\r\\n\")\n >> DataReceived(server1, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHook(Placeholder())\n >> reply(side_effect=redirect(\"http://two.redirect/\"))\n << OpenConnection(server2)\n >> reply(None)\n << SendData(server2, b\"GET / HTTP/1.1\\r\\nHost: two.redirect\\r\\n\\r\\n\")\n >> DataReceived(server2, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert server1().address == (\"one.redirect\", 80)\n assert server2().address == (\"two.redirect\", 80)",
"\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\ndef test_pipelining(tctx, transfer_encoding):\n \"\"\"Test that multiple requests can be processed over the same connection\"\"\"",
" tctx.server.address = (\"example.com\", 80)\n tctx.server.state = ConnectionState.OPEN",
" req = b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\"\n if transfer_encoding == \"identity\":\n resp = (b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 12\\r\\n\"\n b\"\\r\\n\"\n b\"Hello World!\")\n else:\n resp = (b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"\\r\\n\"\n b\"c\\r\\n\"\n b\"Hello World!\\r\\n\"\n b\"0\\r\\n\"\n b\"\\r\\n\")",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent), hooks=False)\n # Roundtrip 1\n >> DataReceived(tctx.client, req)\n << SendData(tctx.server, req)\n >> DataReceived(tctx.server, resp)\n << SendData(tctx.client, resp)\n # Roundtrip 2\n >> DataReceived(tctx.client, req)\n << SendData(tctx.server, req)\n >> DataReceived(tctx.server, resp)\n << SendData(tctx.client, resp)\n )",
"\ndef test_http_reply_from_proxy(tctx):\n \"\"\"Test a response served by mitmproxy itself.\"\"\"",
" def reply_from_proxy(flow: HTTPFlow):\n flow.response = Response.make(418)",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHook(Placeholder())\n >> reply(side_effect=reply_from_proxy)\n << SendData(tctx.client, b\"HTTP/1.1 418 I'm a teapot\\r\\ncontent-length: 0\\r\\n\\r\\n\")\n )",
"\ndef test_response_until_eof(tctx):\n \"\"\"Test scenario where the server response body is terminated by EOF.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\\r\\nfoo\")\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\\r\\nfoo\")\n << CloseConnection(tctx.client)\n )",
"\ndef test_disconnect_while_intercept(tctx):\n \"\"\"Test a server disconnect while a request is intercepted.\"\"\"\n tctx.options.connection_strategy = \"eager\"",
" server1 = Placeholder(Server)\n server2 = Placeholder(Server)\n flow = Placeholder(HTTPFlow)",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpConnectHook(Placeholder(HTTPFlow))\n >> reply()\n << OpenConnection(server1)\n >> reply(None)\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << http.HttpRequestHook(flow)\n >> ConnectionClosed(server1)\n << CloseConnection(server1)\n >> reply(to=-3)\n << OpenConnection(server2)\n >> reply(None)\n << SendData(server2, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server2, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert server1() != server2()\n assert flow().server_conn == server2()\n assert not flow().live",
"\n@pytest.mark.parametrize(\"why\", [\"body_size=0\", \"body_size=3\", \"addon\"])\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\ndef test_response_streaming(tctx, why, transfer_encoding):\n \"\"\"Test HTTP response streaming\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))",
" if why.startswith(\"body_size\"):\n tctx.options.stream_large_bodies = why.replace(\"body_size=\", \"\")",
" def enable_streaming(flow: HTTPFlow):\n if why == \"addon\":\n flow.response.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/largefile HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET /largefile HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\")\n )\n assert flow().live\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(server, b\"Content-Length: 6\\r\\n\\r\\n\"\n b\"abc\")\n else:\n playbook >> DataReceived(server, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")",
" playbook << http.HttpResponseHeadersHook(flow)\n playbook >> reply(side_effect=enable_streaming)",
" if transfer_encoding == \"identity\":\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 6\\r\\n\\r\\n\"\n b\"abc\")\n playbook >> DataReceived(server, b\"def\")\n playbook << SendData(tctx.client, b\"def\")\n else:\n if why == \"body_size=3\":\n playbook >> DataReceived(server, b\"3\\r\\ndef\\r\\n\")\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"6\\r\\nabcdef\\r\\n\")\n else:\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")\n playbook >> DataReceived(server, b\"3\\r\\ndef\\r\\n\")\n playbook << SendData(tctx.client, b\"3\\r\\ndef\\r\\n\")\n playbook >> DataReceived(server, b\"0\\r\\n\\r\\n\")",
" playbook << http.HttpResponseHook(flow)\n playbook >> reply()",
" if transfer_encoding == \"chunked\":\n playbook << SendData(tctx.client, b\"0\\r\\n\\r\\n\")",
" assert playbook\n assert not flow().live",
"\ndef test_stream_modify(tctx):\n \"\"\"Test HTTP stream modification\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)",
" def enable_streaming(flow: HTTPFlow):\n if flow.response is None:\n flow.request.stream = lambda x: b\"[\" + x + b\"]\"\n else:\n flow.response.stream = lambda x: b\"[\" + x + b\"]\"",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"5\\r\\n[abc]\\r\\n\"\n b\"2\\r\\n[]\\r\\n\")\n << http.HttpRequestHook(flow)\n >> reply()\n << SendData(server, b\"0\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\ndef\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"5\\r\\n[def]\\r\\n\"\n b\"2\\r\\n[]\\r\\n\")\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"0\\r\\n\\r\\n\")\n )",
"\n@pytest.mark.parametrize(\"why\", [\"body_size=0\", \"body_size=3\", \"addon\"])\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\n@pytest.mark.parametrize(\"response\", [\"normal response\", \"early response\", \"early close\", \"early kill\"])\ndef test_request_streaming(tctx, why, transfer_encoding, response):\n \"\"\"\n Test HTTP request streaming",
" This is a bit more contrived as we may receive server data while we are still sending the request.\n \"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))",
" if why.startswith(\"body_size\"):\n tctx.options.stream_large_bodies = why.replace(\"body_size=\", \"\")",
" def enable_streaming(flow: HTTPFlow):\n if why == \"addon\":\n flow.request.stream = True",
" playbook >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\")\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(tctx.client, b\"Content-Length: 9\\r\\n\\r\\n\"\n b\"abc\")\n else:\n playbook >> DataReceived(tctx.client, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")",
" playbook << http.HttpRequestHeadersHook(flow)\n playbook >> reply(side_effect=enable_streaming)",
" needs_more_data_before_open = (why == \"body_size=3\" and transfer_encoding == \"chunked\")\n if needs_more_data_before_open:\n playbook >> DataReceived(tctx.client, b\"3\\r\\ndef\\r\\n\")",
" playbook << OpenConnection(server)\n playbook >> reply(None)\n playbook << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\")",
" if transfer_encoding == \"identity\":\n playbook << SendData(server, b\"Content-Length: 9\\r\\n\\r\\n\"\n b\"abc\")\n playbook >> DataReceived(tctx.client, b\"def\")\n playbook << SendData(server, b\"def\")\n else:\n if needs_more_data_before_open:\n playbook << SendData(server, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"6\\r\\nabcdef\\r\\n\")\n else:\n playbook << SendData(server, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")\n playbook >> DataReceived(tctx.client, b\"3\\r\\ndef\\r\\n\")\n playbook << SendData(server, b\"3\\r\\ndef\\r\\n\")",
" if response == \"normal response\":\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(tctx.client, b\"ghi\")\n playbook << SendData(server, b\"ghi\")\n else:\n playbook >> DataReceived(tctx.client, b\"3\\r\\nghi\\r\\n0\\r\\n\\r\\n\")\n playbook << SendData(server, b\"3\\r\\nghi\\r\\n\")",
" playbook << http.HttpRequestHook(flow)\n playbook >> reply()\n if transfer_encoding == \"chunked\":\n playbook << SendData(server, b\"0\\r\\n\\r\\n\")\n assert (\n playbook\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n elif response == \"early response\":\n # We may receive a response before we have finished sending our request.\n # We continue sending unless the server closes the connection.\n # https://tools.ietf.org/html/rfc7231#section-6.5.11\n assert (\n playbook\n >> DataReceived(server, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(tctx.client, b\"ghi\")\n playbook << SendData(server, b\"ghi\")\n else:\n playbook >> DataReceived(tctx.client, b\"3\\r\\nghi\\r\\n0\\r\\n\\r\\n\")\n playbook << SendData(server, b\"3\\r\\nghi\\r\\n\")\n playbook << http.HttpRequestHook(flow)\n playbook >> reply()\n if transfer_encoding == \"chunked\":\n playbook << SendData(server, b\"0\\r\\n\\r\\n\")\n assert playbook\n elif response == \"early close\":\n assert (\n playbook\n >> DataReceived(server, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << CloseConnection(tctx.client)\n )\n elif response == \"early kill\":\n err = Placeholder(bytes)\n assert (\n playbook\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"502 Bad Gateway\" in err()\n else: # pragma: no cover\n assert False",
"\n@pytest.mark.parametrize(\"where\", [\"request\", \"response\"])\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\ndef test_body_size_limit(tctx, where, transfer_encoding):\n \"\"\"Test HTTP request body_size_limit\"\"\"\n tctx.options.body_size_limit = \"3\"\n err = Placeholder(bytes)\n flow = Placeholder(HTTPFlow)",
" if transfer_encoding == \"identity\":\n body = b\"Content-Length: 6\\r\\n\\r\\nabcdef\"\n else:\n body = b\"Transfer-Encoding: chunked\\r\\n\\r\\n6\\r\\nabcdef\"",
" if where == \"request\":\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\" + body)\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"413 Payload Too Large\" in err()\n assert b\"body_size_limit\" in err()\n assert not flow().live\n else:\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\" + body)\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n << CloseConnection(server)\n )\n assert b\"502 Bad Gateway\" in err()\n assert b\"body_size_limit\" in err()\n assert not flow().live",
"\n@pytest.mark.parametrize(\"connect\", [True, False])\ndef test_server_unreachable(tctx, connect):\n \"\"\"Test the scenario where the target server is unreachable.\"\"\"\n tctx.options.connection_strategy = \"eager\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n err = Placeholder(bytes)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n if connect:\n playbook >> DataReceived(tctx.client, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n else:\n playbook >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\\r\\n\")",
" playbook << OpenConnection(server)\n playbook >> reply(\"Connection failed\")\n if not connect:\n # Our API isn't ideal here, there is no error hook for CONNECT requests currently.\n # We could fix this either by having CONNECT request go through all our regular hooks,\n # or by adding dedicated ok/error hooks.\n playbook << http.HttpErrorHook(flow)\n playbook >> reply()\n playbook << SendData(tctx.client, err)\n if not connect:\n playbook << CloseConnection(tctx.client)",
" assert playbook\n if not connect:\n assert flow().error\n assert not flow().live\n assert b\"502 Bad Gateway\" in err()\n assert b\"Connection failed\" in err()",
"\n@pytest.mark.parametrize(\"data\", [\n None,\n b\"I don't speak HTTP.\",\n b\"HTTP/1.1 200 OK\\r\\nContent-Length: 10\\r\\n\\r\\nweee\"\n])\ndef test_server_aborts(tctx, data):\n \"\"\"Test the scenario where the server doesn't serve a response\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n err = Placeholder(bytes)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n )\n if data:\n playbook >> DataReceived(server, data)\n assert (\n playbook\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert flow().error\n assert b\"502 Bad Gateway\" in err()\n assert not flow().live",
"\n@pytest.mark.parametrize(\"redirect\", [\"\", \"change-destination\", \"change-proxy\"])\n@pytest.mark.parametrize(\"scheme\", [\"http\", \"https\"])\ndef test_upstream_proxy(tctx, redirect, scheme):\n \"\"\"Test that an upstream HTTP proxy is used.\"\"\"\n server = Placeholder(Server)\n server2 = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n tctx.options.mode = \"upstream:http://proxy:8080\"\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.upstream), hooks=False)",
" if scheme == \"http\":\n assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n )",
" else:\n assert (\n playbook\n >> DataReceived(tctx.client, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n )",
" playbook >> DataReceived(server, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n playbook << SendData(tctx.client, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")",
" assert playbook\n assert server().address == (\"proxy\", 8080)",
" if scheme == \"http\":\n playbook >> DataReceived(tctx.client, b\"GET http://example.com/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n else:\n playbook >> DataReceived(tctx.client, b\"GET /two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")",
" assert (playbook << http.HttpRequestHook(flow))\n if redirect == \"change-destination\":\n flow().request.host = \"other-server\"\n flow().request.host_header = \"example.com\"\n elif redirect == \"change-proxy\":\n flow().server_conn.via = ServerSpec(\"http\", address=(\"other-proxy\", 1234))\n playbook >> reply()",
" if redirect:\n # Protocol-wise we wouldn't need to open a new connection for plain http host redirects,\n # but we disregard this edge case to simplify implementation.\n playbook << OpenConnection(server2)\n playbook >> reply(None)\n else:\n server2 = server",
" if scheme == \"http\":\n if redirect == \"change-destination\":\n playbook << SendData(server2, b\"GET http://other-server/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n else:\n playbook << SendData(server2, b\"GET http://example.com/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n else:\n if redirect == \"change-destination\":\n playbook << SendData(server2, b\"CONNECT other-server:443 HTTP/1.1\\r\\n\\r\\n\")\n playbook >> DataReceived(server2, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n elif redirect == \"change-proxy\":\n playbook << SendData(server2, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n playbook >> DataReceived(server2, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n playbook << SendData(server2, b\"GET /two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")",
" playbook >> DataReceived(server2, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n playbook << SendData(tctx.client, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")",
" assert playbook",
" if redirect == \"change-destination\":\n assert flow().server_conn.address[0] == \"other-server\"\n else:\n assert flow().server_conn.address[0] == \"example.com\"",
" if redirect == \"change-proxy\":\n assert server2().address == flow().server_conn.via.address == (\"other-proxy\", 1234)\n else:\n assert server2().address == flow().server_conn.via.address == (\"proxy\", 8080)",
" assert (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )",
"\n@pytest.mark.parametrize(\"mode\", [\"regular\", \"upstream\"])\n@pytest.mark.parametrize(\"close_first\", [\"client\", \"server\"])\ndef test_http_proxy_tcp(tctx, mode, close_first):\n \"\"\"Test TCP over HTTP CONNECT.\"\"\"\n server = Placeholder(Server)\n f = Placeholder(TCPFlow)\n tctx.options.connection_strategy = \"lazy\"",
" if mode == \"upstream\":\n tctx.options.mode = \"upstream:http://proxy:8080\"\n toplayer = http.HttpLayer(tctx, HTTPMode.upstream)\n else:\n tctx.options.mode = \"regular\"\n toplayer = http.HttpLayer(tctx, HTTPMode.regular)",
" playbook = Playbook(toplayer, hooks=False)\n assert (\n playbook\n >> DataReceived(tctx.client, b\"CONNECT example:443 HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n >> DataReceived(tctx.client, b\"this is not http\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: TCPLayer(ctx, ignore=False))\n << TcpStartHook(f)\n >> reply()\n << OpenConnection(server)\n )",
" playbook >> reply(None)\n if mode == \"upstream\":\n playbook << SendData(server, b\"CONNECT example:443 HTTP/1.1\\r\\n\\r\\n\")\n playbook >> DataReceived(server, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")",
" assert (\n playbook\n << SendData(server, b\"this is not http\")\n >> DataReceived(server, b\"true that\")\n << SendData(tctx.client, b\"true that\")\n )",
" if mode == \"regular\":\n assert server().address == (\"example\", 443)\n else:\n assert server().address == (\"proxy\", 8080)",
" assert (\n playbook\n >> TcpMessageInjected(f, TCPMessage(False, b\"fake news from your friendly man-in-the-middle\"))\n << SendData(tctx.client, b\"fake news from your friendly man-in-the-middle\")\n )",
" if close_first == \"client\":\n a, b = tctx.client, server\n else:\n a, b = server, tctx.client\n assert (\n playbook\n >> ConnectionClosed(a)\n << CloseConnection(b)\n >> ConnectionClosed(b)\n << CloseConnection(a)\n )",
"\n@pytest.mark.parametrize(\"strategy\", [\"eager\", \"lazy\"])\ndef test_proxy_chain(tctx, strategy):\n server = Placeholder(Server)\n tctx.options.connection_strategy = strategy\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)",
" playbook >> DataReceived(tctx.client, b\"CONNECT proxy:8080 HTTP/1.1\\r\\n\\r\\n\")\n if strategy == \"eager\":\n playbook << OpenConnection(server)\n playbook >> reply(None)\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")",
" playbook >> DataReceived(tctx.client, b\"CONNECT second-proxy:8080 HTTP/1.1\\r\\n\\r\\n\")\n playbook << layer.NextLayerHook(Placeholder())\n playbook >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n playbook << SendData(tctx.client,\n b\"HTTP/1.1 502 Bad Gateway\\r\\n\"\n b\"content-length: 198\\r\\n\"\n b\"\\r\\n\"\n b\"mitmproxy received an HTTP CONNECT request even though it is not running in regular/upstream mode. \"\n b\"This usually indicates a misconfiguration, please see the mitmproxy mode documentation for details.\")",
" assert playbook",
"\ndef test_no_headers(tctx):\n \"\"\"Test that we can correctly reassemble requests/responses with no headers.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n )\n assert server().address == (\"example.com\", 80)",
"\ndef test_http_proxy_relative_request(tctx):\n \"\"\"Test handling of a relative-form \"GET /\" in regular proxy mode.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n )\n assert server().address == (\"example.com\", 80)",
"\ndef test_http_proxy_relative_request_no_host_header(tctx):\n \"\"\"Test handling of a relative-form \"GET /\" in regular proxy mode, but without a host header.\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"400 Bad Request\" in err()\n assert b\"HTTP request has no host header, destination unknown.\" in err()",
"\ndef test_http_expect(tctx):\n \"\"\"Test handling of a 'Expect: 100-continue' header.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"PUT http://example.com/large-file HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 15\\r\\n\"\n b\"Expect: 100-continue\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 100 Continue\\r\\n\\r\\n\")\n >> DataReceived(tctx.client, b\"lots of content\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"PUT /large-file HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 15\\r\\n\\r\\n\"\n b\"lots of content\")\n >> DataReceived(server, b\"HTTP/1.1 201 Created\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 201 Created\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert server().address == (\"example.com\", 80)",
"\n@pytest.mark.parametrize(\"stream\", [True, False])\ndef test_http_client_aborts(tctx, stream):\n \"\"\"Test handling of the case where a client aborts during request transmission.\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=True)",
" def enable_streaming(flow: HTTPFlow):\n flow.request.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n << http.HttpRequestHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_streaming)\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n )\n else:\n assert playbook >> reply()\n (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )\n if stream:\n playbook << CloseConnection(server)\n assert (\n playbook\n << http.HttpErrorHook(flow)\n >> reply()\n << None\n )",
" assert \"peer closed connection\" in flow().error.msg\n assert not flow().live",
"\n@pytest.mark.parametrize(\"stream\", [True, False])\ndef test_http_server_aborts(tctx, stream):\n \"\"\"Test handling of the case where a server aborts during response transmission.\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))",
" def enable_streaming(flow: HTTPFlow):\n flow.response.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n << http.HttpResponseHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_streaming)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n )\n else:\n assert playbook >> reply()\n assert (\n playbook\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply()\n << CloseConnection(tctx.client)\n )\n else:\n error_html = Placeholder(bytes)\n assert (\n playbook\n >> reply()\n << SendData(tctx.client, error_html)\n << CloseConnection(tctx.client)\n )\n assert b\"502 Bad Gateway\" in error_html()\n assert b\"peer closed connection\" in error_html()",
" assert \"peer closed connection\" in flow().error.msg\n assert not flow().live",
"\n@pytest.mark.parametrize(\"when\", [\"http_connect\", \"requestheaders\", \"request\", \"script-response-responseheaders\",\n \"responseheaders\",\n \"response\", \"error\"])\ndef test_kill_flow(tctx, when):\n \"\"\"Test that we properly kill flows if instructed to do so\"\"\"\n tctx.options.connection_strategy = \"lazy\"\n server = Placeholder(Server)\n connect_flow = Placeholder(HTTPFlow)\n flow = Placeholder(HTTPFlow)",
" def kill(flow: HTTPFlow):\n # Can't use flow.kill() here because that currently still depends on a reply object.\n flow.error = Error(Error.KILLED_MESSAGE)",
" def assert_kill(err_hook: bool = True):\n playbook >> reply(side_effect=kill)\n if err_hook:\n playbook << http.HttpErrorHook(flow)\n playbook >> reply()\n playbook << CloseConnection(tctx.client)\n assert playbook\n if flow():\n assert not flow().live",
" playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n assert (playbook\n >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpConnectHook(connect_flow))\n if when == \"http_connect\":\n return assert_kill(False)\n assert (playbook\n >> reply()\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << http.HttpRequestHeadersHook(flow))\n if when == \"requestheaders\":\n return assert_kill()\n assert (playbook\n >> reply()\n << http.HttpRequestHook(flow))\n if when == \"request\":\n return assert_kill()\n if when == \"script-response-responseheaders\":\n assert (playbook\n >> reply(side_effect=lambda f: setattr(f, \"response\", Response.make()))\n << http.HttpResponseHeadersHook(flow))\n return assert_kill()\n assert (playbook\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World\")\n << http.HttpResponseHeadersHook(flow))\n if when == \"responseheaders\":\n return assert_kill()",
" if when == \"response\":\n assert (playbook\n >> reply()\n >> DataReceived(server, b\"!\")\n << http.HttpResponseHook(flow))\n return assert_kill(False)\n elif when == \"error\":\n assert (playbook\n >> reply()\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow))\n return assert_kill(False)\n else:\n raise AssertionError",
"\ndef test_close_during_connect_hook(tctx):\n flow = Placeholder(HTTPFlow)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client,\n b'CONNECT hi.ls:443 HTTP/1.1\\r\\n'\n b'Proxy-Connection: keep-alive\\r\\n'\n b'Connection: keep-alive\\r\\n'\n b'Host: hi.ls:443\\r\\n\\r\\n')\n << http.HttpConnectHook(flow)\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n >> reply(to=-3)\n )",
"\n@pytest.mark.parametrize(\"client_close\", [b\"\", b\"Connection: close\\r\\n\"])\n@pytest.mark.parametrize(\"server_close\", [b\"\", b\"Connection: close\\r\\n\"])\ndef test_connection_close_header(tctx, client_close, server_close):\n \"\"\"Test that we correctly close connections if we have a `Connection: close` header.\"\"\"\n if not client_close and not server_close:\n return\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example/ HTTP/1.1\\r\\n\"\n b\"Host: example\\r\\n\" + client_close +\n b\"\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example\\r\\n\" + client_close +\n b\"\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\" + server_close +\n b\"\\r\\n\")\n << CloseConnection(server)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\" + server_close +\n b\"\\r\\n\")\n << CloseConnection(tctx.client)\n )",
"\n@pytest.mark.parametrize(\"proto\", [\"websocket\", \"tcp\", \"none\"])\ndef test_upgrade(tctx, proto):\n \"\"\"Test a HTTP -> WebSocket upgrade with different protocols enabled\"\"\"\n if proto != \"websocket\":\n tctx.options.websocket = False\n if proto != \"tcp\":\n tctx.options.rawtcp = False",
" tctx.server.address = (\"example.com\", 80)\n tctx.server.state = ConnectionState.OPEN\n http_flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.transparent))\n (\n playbook\n >> DataReceived(tctx.client,\n b\"GET / HTTP/1.1\\r\\n\"\n b\"Connection: upgrade\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Sec-WebSocket-Version: 13\\r\\n\"\n b\"\\r\\n\")\n << http.HttpRequestHeadersHook(http_flow)\n >> reply()\n << http.HttpRequestHook(http_flow)\n >> reply()\n << SendData(tctx.server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Connection: upgrade\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Sec-WebSocket-Version: 13\\r\\n\"\n b\"\\r\\n\")\n >> DataReceived(tctx.server, b\"HTTP/1.1 101 Switching Protocols\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Connection: Upgrade\\r\\n\"\n b\"\\r\\n\")\n << http.HttpResponseHeadersHook(http_flow)\n >> reply()\n << http.HttpResponseHook(http_flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 101 Switching Protocols\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Connection: Upgrade\\r\\n\"\n b\"\\r\\n\")\n )\n if proto == \"websocket\":\n assert playbook << WebsocketStartHook(http_flow)\n elif proto == \"tcp\":\n assert playbook << TcpStartHook(Placeholder(TCPFlow))\n else:\n assert (\n playbook\n << Log(\"Sent HTTP 101 response, but no protocol is enabled to upgrade to.\", \"warn\")\n << CloseConnection(tctx.client)\n )",
"\ndef test_dont_reuse_closed(tctx):\n \"\"\"Test that a closed connection is not reused.\"\"\"\n server = Placeholder(Server)\n server2 = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n >> ConnectionClosed(server)\n << CloseConnection(server)\n >> DataReceived(tctx.client, b\"GET http://example.com/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server2)\n >> reply(None)\n << SendData(server2, b\"GET /two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server2, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )",
"\ndef test_reuse_error(tctx):\n \"\"\"Test that an errored connection is reused.\"\"\"\n tctx.server.address = (\"example.com\", 443)\n tctx.server.error = \"tls verify failed\"\n error_html = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent), hooks=False)\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, error_html)\n << CloseConnection(tctx.client)\n )\n assert b\"502 Bad Gateway\" in error_html()\n assert b\"tls verify failed\" in error_html()",
"\ndef test_transparent_sni(tctx):\n \"\"\"Test that we keep the SNI in lazy transparent mode.\"\"\"\n tctx.client.sni = \"example.com\"\n tctx.server.address = (\"192.0.2.42\", 443)\n tctx.server.tls = True",
" flow = Placeholder(HTTPFlow)",
" server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent))\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n )\n assert server().address == (\"192.0.2.42\", 443)\n assert server().sni == \"example.com\"",
"\ndef test_original_server_disconnects(tctx):\n \"\"\"Test that we correctly handle the case where the initial server conn is just closed.\"\"\"\n tctx.server.state = ConnectionState.OPEN\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent))\n >> ConnectionClosed(tctx.server)\n << CloseConnection(tctx.server)\n )",
"\ndef test_request_smuggling(tctx):\n \"\"\"Test that we reject request smuggling\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 42\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\")\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Received both a Transfer-Encoding and a Content-Length header\" in err()",
"",
"",
"def test_request_smuggling_te_te(tctx):\n \"\"\"Test that we reject transfer-encoding headers that are weird in some way\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, (\"GET http://example.com/ HTTP/1.1\\r\\n\"\n \"Host: example.com\\r\\n\"\n \"Transfer-Encoding: chunKed\\r\\n\\r\\n\").encode()) # note the non-standard \"K\"\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Invalid transfer encoding\" in err()",
"\ndef test_invalid_content_length(tctx):\n \"\"\"Test that we still trigger flow hooks for requests with semantic errors\"\"\"\n err = Placeholder(bytes)\n flow = Placeholder(HTTPFlow)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, (\"GET http://example.com/ HTTP/1.1\\r\\n\"\n \"Host: example.com\\r\\n\"\n \"Content-Length: NaN\\r\\n\\r\\n\").encode())\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpErrorHook(flow)\n >> reply()\n )\n assert b\"Invalid Content-Length header\" in err()",
"\ndef test_chunked_and_content_length_set_by_addon(tctx):\n \"\"\"Test that we don't crash when an addon sets a transfer-encoding header",
" We reject a request with both transfer-encoding and content-length header to\n thwart request smuggling, but if a user explicitly sets it we should not crash.\n \"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)",
" def make_chunked(flow: HTTPFlow):\n if flow.response:\n flow.response.headers[\"Transfer-Encoding\"] = \"chunked\"\n else:\n flow.request.headers[\"Transfer-Encoding\"] = \"chunked\"",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 0\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply(side_effect=make_chunked)\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 0\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply(side_effect=make_chunked)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n )",
"\ndef test_connect_more_newlines(tctx):\n \"\"\"Ignore superfluous \\r\\n in CONNECT request, https://github.com/mitmproxy/mitmproxy/issues/4870\"\"\"\n server = Placeholder(Server)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n nl = Placeholder(layer.NextLayer)",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\\r\\n\")\n << http.HttpConnectHook(Placeholder())\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"\\x16\\x03\\x03\\x00\\xb3\\x01\\x00\\x00\\xaf\\x03\\x03\")\n << layer.NextLayerHook(nl)\n )\n assert nl().data_client() == b\"\\x16\\x03\\x03\\x00\\xb3\\x01\\x00\\x00\\xaf\\x03\\x03\""
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import pytest",
"from mitmproxy.connection import ConnectionState, Server\nfrom mitmproxy.flow import Error\nfrom mitmproxy.http import HTTPFlow, Response\nfrom mitmproxy.net.server_spec import ServerSpec\nfrom mitmproxy.proxy import layer\nfrom mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData\nfrom mitmproxy.proxy.events import ConnectionClosed, DataReceived\nfrom mitmproxy.proxy.layers import TCPLayer, http, tls\nfrom mitmproxy.proxy.layers.http import HTTPMode\nfrom mitmproxy.proxy.layers.tcp import TcpMessageInjected, TcpStartHook\nfrom mitmproxy.proxy.layers.websocket import WebsocketStartHook\nfrom mitmproxy.tcp import TCPFlow, TCPMessage\nfrom test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply, reply_next_layer",
"\ndef test_http_proxy(tctx):\n \"\"\"Test a simple HTTP GET / request\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"GET http://example.com/foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n >> DataReceived(server, b\"!\")\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")\n )\n assert server().address == (\"example.com\", 80)",
"\n@pytest.mark.parametrize(\"strategy\", [\"lazy\", \"eager\"])\ndef test_https_proxy(strategy, tctx):\n \"\"\"Test a CONNECT request, followed by a HTTP GET /\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n tctx.options.connection_strategy = strategy",
" (playbook\n >> DataReceived(tctx.client, b\"CONNECT example.proxy:80 HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpConnectHook(Placeholder())\n >> reply())\n if strategy == \"eager\":\n (playbook\n << OpenConnection(server)\n >> reply(None))\n (playbook\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply())\n if strategy == \"lazy\":\n (playbook\n << OpenConnection(server)\n >> reply(None))\n (playbook\n << SendData(server, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\"))\n assert playbook",
"\n@pytest.mark.parametrize(\"https_client\", [False, True])\n@pytest.mark.parametrize(\"https_server\", [False, True])\n@pytest.mark.parametrize(\"strategy\", [\"lazy\", \"eager\"])\ndef test_redirect(strategy, https_server, https_client, tctx, monkeypatch):\n \"\"\"Test redirects between http:// and https:// in regular proxy mode.\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n tctx.options.connection_strategy = strategy\n p = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)",
" if https_server:\n monkeypatch.setattr(tls, \"ServerTLSLayer\", tls.MockTLSLayer)",
" def redirect(flow: HTTPFlow):\n if https_server:\n flow.request.url = \"https://redirected.site/\"\n else:\n flow.request.url = \"http://redirected.site/\"",
" if https_client:\n p >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\")\n if strategy == \"eager\":\n p << OpenConnection(Placeholder())\n p >> reply(None)\n p << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n p >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n p << layer.NextLayerHook(Placeholder())\n p >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n else:\n p >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n p << http.HttpRequestHook(flow)\n p >> reply(side_effect=redirect)\n p << OpenConnection(server)\n p >> reply(None)\n p << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: redirected.site\\r\\n\\r\\n\")\n p >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")\n p << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World!\")",
" assert p\n if https_server:\n assert server().address == (\"redirected.site\", 443)\n else:\n assert server().address == (\"redirected.site\", 80)",
"\ndef test_multiple_server_connections(tctx):\n \"\"\"Test multiple requests being rewritten to different targets.\"\"\"\n server1 = Placeholder(Server)\n server2 = Placeholder(Server)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)",
" def redirect(to: str):\n def side_effect(flow: HTTPFlow):\n flow.request.url = to",
" return side_effect",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHook(Placeholder())\n >> reply(side_effect=redirect(\"http://one.redirect/\"))\n << OpenConnection(server1)\n >> reply(None)\n << SendData(server1, b\"GET / HTTP/1.1\\r\\nHost: one.redirect\\r\\n\\r\\n\")\n >> DataReceived(server1, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHook(Placeholder())\n >> reply(side_effect=redirect(\"http://two.redirect/\"))\n << OpenConnection(server2)\n >> reply(None)\n << SendData(server2, b\"GET / HTTP/1.1\\r\\nHost: two.redirect\\r\\n\\r\\n\")\n >> DataReceived(server2, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert server1().address == (\"one.redirect\", 80)\n assert server2().address == (\"two.redirect\", 80)",
"\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\ndef test_pipelining(tctx, transfer_encoding):\n \"\"\"Test that multiple requests can be processed over the same connection\"\"\"",
" tctx.server.address = (\"example.com\", 80)\n tctx.server.state = ConnectionState.OPEN",
" req = b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\"\n if transfer_encoding == \"identity\":\n resp = (b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 12\\r\\n\"\n b\"\\r\\n\"\n b\"Hello World!\")\n else:\n resp = (b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"\\r\\n\"\n b\"c\\r\\n\"\n b\"Hello World!\\r\\n\"\n b\"0\\r\\n\"\n b\"\\r\\n\")",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent), hooks=False)\n # Roundtrip 1\n >> DataReceived(tctx.client, req)\n << SendData(tctx.server, req)\n >> DataReceived(tctx.server, resp)\n << SendData(tctx.client, resp)\n # Roundtrip 2\n >> DataReceived(tctx.client, req)\n << SendData(tctx.server, req)\n >> DataReceived(tctx.server, resp)\n << SendData(tctx.client, resp)\n )",
"\ndef test_http_reply_from_proxy(tctx):\n \"\"\"Test a response served by mitmproxy itself.\"\"\"",
" def reply_from_proxy(flow: HTTPFlow):\n flow.response = Response.make(418)",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHook(Placeholder())\n >> reply(side_effect=reply_from_proxy)\n << SendData(tctx.client, b\"HTTP/1.1 418 I'm a teapot\\r\\ncontent-length: 0\\r\\n\\r\\n\")\n )",
"\ndef test_response_until_eof(tctx):\n \"\"\"Test scenario where the server response body is terminated by EOF.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\\r\\nfoo\")\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\\r\\nfoo\")\n << CloseConnection(tctx.client)\n )",
"\ndef test_disconnect_while_intercept(tctx):\n \"\"\"Test a server disconnect while a request is intercepted.\"\"\"\n tctx.options.connection_strategy = \"eager\"",
" server1 = Placeholder(Server)\n server2 = Placeholder(Server)\n flow = Placeholder(HTTPFlow)",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpConnectHook(Placeholder(HTTPFlow))\n >> reply()\n << OpenConnection(server1)\n >> reply(None)\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << http.HttpRequestHook(flow)\n >> ConnectionClosed(server1)\n << CloseConnection(server1)\n >> reply(to=-3)\n << OpenConnection(server2)\n >> reply(None)\n << SendData(server2, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server2, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert server1() != server2()\n assert flow().server_conn == server2()\n assert not flow().live",
"\n@pytest.mark.parametrize(\"why\", [\"body_size=0\", \"body_size=3\", \"addon\"])\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\ndef test_response_streaming(tctx, why, transfer_encoding):\n \"\"\"Test HTTP response streaming\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))",
" if why.startswith(\"body_size\"):\n tctx.options.stream_large_bodies = why.replace(\"body_size=\", \"\")",
" def enable_streaming(flow: HTTPFlow):\n if why == \"addon\":\n flow.response.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/largefile HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET /largefile HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\")\n )\n assert flow().live\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(server, b\"Content-Length: 6\\r\\n\\r\\n\"\n b\"abc\")\n else:\n playbook >> DataReceived(server, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")",
" playbook << http.HttpResponseHeadersHook(flow)\n playbook >> reply(side_effect=enable_streaming)",
" if transfer_encoding == \"identity\":\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 6\\r\\n\\r\\n\"\n b\"abc\")\n playbook >> DataReceived(server, b\"def\")\n playbook << SendData(tctx.client, b\"def\")\n else:\n if why == \"body_size=3\":\n playbook >> DataReceived(server, b\"3\\r\\ndef\\r\\n\")\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"6\\r\\nabcdef\\r\\n\")\n else:\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")\n playbook >> DataReceived(server, b\"3\\r\\ndef\\r\\n\")\n playbook << SendData(tctx.client, b\"3\\r\\ndef\\r\\n\")\n playbook >> DataReceived(server, b\"0\\r\\n\\r\\n\")",
" playbook << http.HttpResponseHook(flow)\n playbook >> reply()",
" if transfer_encoding == \"chunked\":\n playbook << SendData(tctx.client, b\"0\\r\\n\\r\\n\")",
" assert playbook\n assert not flow().live",
"\ndef test_stream_modify(tctx):\n \"\"\"Test HTTP stream modification\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)",
" def enable_streaming(flow: HTTPFlow):\n if flow.response is None:\n flow.request.stream = lambda x: b\"[\" + x + b\"]\"\n else:\n flow.response.stream = lambda x: b\"[\" + x + b\"]\"",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"5\\r\\n[abc]\\r\\n\"\n b\"2\\r\\n[]\\r\\n\")\n << http.HttpRequestHook(flow)\n >> reply()\n << SendData(server, b\"0\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\ndef\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"5\\r\\n[def]\\r\\n\"\n b\"2\\r\\n[]\\r\\n\")\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"0\\r\\n\\r\\n\")\n )",
"\n@pytest.mark.parametrize(\"why\", [\"body_size=0\", \"body_size=3\", \"addon\"])\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\n@pytest.mark.parametrize(\"response\", [\"normal response\", \"early response\", \"early close\", \"early kill\"])\ndef test_request_streaming(tctx, why, transfer_encoding, response):\n \"\"\"\n Test HTTP request streaming",
" This is a bit more contrived as we may receive server data while we are still sending the request.\n \"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))",
" if why.startswith(\"body_size\"):\n tctx.options.stream_large_bodies = why.replace(\"body_size=\", \"\")",
" def enable_streaming(flow: HTTPFlow):\n if why == \"addon\":\n flow.request.stream = True",
" playbook >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\")\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(tctx.client, b\"Content-Length: 9\\r\\n\\r\\n\"\n b\"abc\")\n else:\n playbook >> DataReceived(tctx.client, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")",
" playbook << http.HttpRequestHeadersHook(flow)\n playbook >> reply(side_effect=enable_streaming)",
" needs_more_data_before_open = (why == \"body_size=3\" and transfer_encoding == \"chunked\")\n if needs_more_data_before_open:\n playbook >> DataReceived(tctx.client, b\"3\\r\\ndef\\r\\n\")",
" playbook << OpenConnection(server)\n playbook >> reply(None)\n playbook << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\")",
" if transfer_encoding == \"identity\":\n playbook << SendData(server, b\"Content-Length: 9\\r\\n\\r\\n\"\n b\"abc\")\n playbook >> DataReceived(tctx.client, b\"def\")\n playbook << SendData(server, b\"def\")\n else:\n if needs_more_data_before_open:\n playbook << SendData(server, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"6\\r\\nabcdef\\r\\n\")\n else:\n playbook << SendData(server, b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"3\\r\\nabc\\r\\n\")\n playbook >> DataReceived(tctx.client, b\"3\\r\\ndef\\r\\n\")\n playbook << SendData(server, b\"3\\r\\ndef\\r\\n\")",
" if response == \"normal response\":\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(tctx.client, b\"ghi\")\n playbook << SendData(server, b\"ghi\")\n else:\n playbook >> DataReceived(tctx.client, b\"3\\r\\nghi\\r\\n0\\r\\n\\r\\n\")\n playbook << SendData(server, b\"3\\r\\nghi\\r\\n\")",
" playbook << http.HttpRequestHook(flow)\n playbook >> reply()\n if transfer_encoding == \"chunked\":\n playbook << SendData(server, b\"0\\r\\n\\r\\n\")\n assert (\n playbook\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n elif response == \"early response\":\n # We may receive a response before we have finished sending our request.\n # We continue sending unless the server closes the connection.\n # https://tools.ietf.org/html/rfc7231#section-6.5.11\n assert (\n playbook\n >> DataReceived(server, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n if transfer_encoding == \"identity\":\n playbook >> DataReceived(tctx.client, b\"ghi\")\n playbook << SendData(server, b\"ghi\")\n else:\n playbook >> DataReceived(tctx.client, b\"3\\r\\nghi\\r\\n0\\r\\n\\r\\n\")\n playbook << SendData(server, b\"3\\r\\nghi\\r\\n\")\n playbook << http.HttpRequestHook(flow)\n playbook >> reply()\n if transfer_encoding == \"chunked\":\n playbook << SendData(server, b\"0\\r\\n\\r\\n\")\n assert playbook\n elif response == \"early close\":\n assert (\n playbook\n >> DataReceived(server, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 413 Request Entity Too Large\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << CloseConnection(tctx.client)\n )\n elif response == \"early kill\":\n err = Placeholder(bytes)\n assert (\n playbook\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"502 Bad Gateway\" in err()\n else: # pragma: no cover\n assert False",
"\n@pytest.mark.parametrize(\"where\", [\"request\", \"response\"])\n@pytest.mark.parametrize(\"transfer_encoding\", [\"identity\", \"chunked\"])\ndef test_body_size_limit(tctx, where, transfer_encoding):\n \"\"\"Test HTTP request body_size_limit\"\"\"\n tctx.options.body_size_limit = \"3\"\n err = Placeholder(bytes)\n flow = Placeholder(HTTPFlow)",
" if transfer_encoding == \"identity\":\n body = b\"Content-Length: 6\\r\\n\\r\\nabcdef\"\n else:\n body = b\"Transfer-Encoding: chunked\\r\\n\\r\\n6\\r\\nabcdef\"",
" if where == \"request\":\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\" + body)\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"413 Payload Too Large\" in err()\n assert b\"body_size_limit\" in err()\n assert not flow().live\n else:\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\" + body)\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n << CloseConnection(server)\n )\n assert b\"502 Bad Gateway\" in err()\n assert b\"body_size_limit\" in err()\n assert not flow().live",
"\n@pytest.mark.parametrize(\"connect\", [True, False])\ndef test_server_unreachable(tctx, connect):\n \"\"\"Test the scenario where the target server is unreachable.\"\"\"\n tctx.options.connection_strategy = \"eager\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n err = Placeholder(bytes)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n if connect:\n playbook >> DataReceived(tctx.client, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n else:\n playbook >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\\r\\n\")",
" playbook << OpenConnection(server)\n playbook >> reply(\"Connection failed\")\n if not connect:\n # Our API isn't ideal here, there is no error hook for CONNECT requests currently.\n # We could fix this either by having CONNECT request go through all our regular hooks,\n # or by adding dedicated ok/error hooks.\n playbook << http.HttpErrorHook(flow)\n playbook >> reply()\n playbook << SendData(tctx.client, err)\n if not connect:\n playbook << CloseConnection(tctx.client)",
" assert playbook\n if not connect:\n assert flow().error\n assert not flow().live\n assert b\"502 Bad Gateway\" in err()\n assert b\"Connection failed\" in err()",
"\n@pytest.mark.parametrize(\"data\", [\n None,\n b\"I don't speak HTTP.\",\n b\"HTTP/1.1 200 OK\\r\\nContent-Length: 10\\r\\n\\r\\nweee\"\n])\ndef test_server_aborts(tctx, data):\n \"\"\"Test the scenario where the server doesn't serve a response\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n err = Placeholder(bytes)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n )\n if data:\n playbook >> DataReceived(server, data)\n assert (\n playbook\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert flow().error\n assert b\"502 Bad Gateway\" in err()\n assert not flow().live",
"\n@pytest.mark.parametrize(\"redirect\", [\"\", \"change-destination\", \"change-proxy\"])\n@pytest.mark.parametrize(\"scheme\", [\"http\", \"https\"])\ndef test_upstream_proxy(tctx, redirect, scheme):\n \"\"\"Test that an upstream HTTP proxy is used.\"\"\"\n server = Placeholder(Server)\n server2 = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n tctx.options.mode = \"upstream:http://proxy:8080\"\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.upstream), hooks=False)",
" if scheme == \"http\":\n assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n )",
" else:\n assert (\n playbook\n >> DataReceived(tctx.client, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n )",
" playbook >> DataReceived(server, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n playbook << SendData(tctx.client, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")",
" assert playbook\n assert server().address == (\"proxy\", 8080)",
" if scheme == \"http\":\n playbook >> DataReceived(tctx.client, b\"GET http://example.com/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n else:\n playbook >> DataReceived(tctx.client, b\"GET /two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")",
" assert (playbook << http.HttpRequestHook(flow))\n if redirect == \"change-destination\":\n flow().request.host = \"other-server\"\n flow().request.host_header = \"example.com\"\n elif redirect == \"change-proxy\":\n flow().server_conn.via = ServerSpec(\"http\", address=(\"other-proxy\", 1234))\n playbook >> reply()",
" if redirect:\n # Protocol-wise we wouldn't need to open a new connection for plain http host redirects,\n # but we disregard this edge case to simplify implementation.\n playbook << OpenConnection(server2)\n playbook >> reply(None)\n else:\n server2 = server",
" if scheme == \"http\":\n if redirect == \"change-destination\":\n playbook << SendData(server2, b\"GET http://other-server/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n else:\n playbook << SendData(server2, b\"GET http://example.com/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n else:\n if redirect == \"change-destination\":\n playbook << SendData(server2, b\"CONNECT other-server:443 HTTP/1.1\\r\\n\\r\\n\")\n playbook >> DataReceived(server2, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n elif redirect == \"change-proxy\":\n playbook << SendData(server2, b\"CONNECT example.com:443 HTTP/1.1\\r\\n\\r\\n\")\n playbook >> DataReceived(server2, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n playbook << SendData(server2, b\"GET /two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")",
" playbook >> DataReceived(server2, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n playbook << SendData(tctx.client, b\"HTTP/1.1 418 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")",
" assert playbook",
" if redirect == \"change-destination\":\n assert flow().server_conn.address[0] == \"other-server\"\n else:\n assert flow().server_conn.address[0] == \"example.com\"",
" if redirect == \"change-proxy\":\n assert server2().address == flow().server_conn.via.address == (\"other-proxy\", 1234)\n else:\n assert server2().address == flow().server_conn.via.address == (\"proxy\", 8080)",
" assert (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )",
"\n@pytest.mark.parametrize(\"mode\", [\"regular\", \"upstream\"])\n@pytest.mark.parametrize(\"close_first\", [\"client\", \"server\"])\ndef test_http_proxy_tcp(tctx, mode, close_first):\n \"\"\"Test TCP over HTTP CONNECT.\"\"\"\n server = Placeholder(Server)\n f = Placeholder(TCPFlow)\n tctx.options.connection_strategy = \"lazy\"",
" if mode == \"upstream\":\n tctx.options.mode = \"upstream:http://proxy:8080\"\n toplayer = http.HttpLayer(tctx, HTTPMode.upstream)\n else:\n tctx.options.mode = \"regular\"\n toplayer = http.HttpLayer(tctx, HTTPMode.regular)",
" playbook = Playbook(toplayer, hooks=False)\n assert (\n playbook\n >> DataReceived(tctx.client, b\"CONNECT example:443 HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")\n >> DataReceived(tctx.client, b\"this is not http\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: TCPLayer(ctx, ignore=False))\n << TcpStartHook(f)\n >> reply()\n << OpenConnection(server)\n )",
" playbook >> reply(None)\n if mode == \"upstream\":\n playbook << SendData(server, b\"CONNECT example:443 HTTP/1.1\\r\\n\\r\\n\")\n playbook >> DataReceived(server, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")",
" assert (\n playbook\n << SendData(server, b\"this is not http\")\n >> DataReceived(server, b\"true that\")\n << SendData(tctx.client, b\"true that\")\n )",
" if mode == \"regular\":\n assert server().address == (\"example\", 443)\n else:\n assert server().address == (\"proxy\", 8080)",
" assert (\n playbook\n >> TcpMessageInjected(f, TCPMessage(False, b\"fake news from your friendly man-in-the-middle\"))\n << SendData(tctx.client, b\"fake news from your friendly man-in-the-middle\")\n )",
" if close_first == \"client\":\n a, b = tctx.client, server\n else:\n a, b = server, tctx.client\n assert (\n playbook\n >> ConnectionClosed(a)\n << CloseConnection(b)\n >> ConnectionClosed(b)\n << CloseConnection(a)\n )",
"\n@pytest.mark.parametrize(\"strategy\", [\"eager\", \"lazy\"])\ndef test_proxy_chain(tctx, strategy):\n server = Placeholder(Server)\n tctx.options.connection_strategy = strategy\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)",
" playbook >> DataReceived(tctx.client, b\"CONNECT proxy:8080 HTTP/1.1\\r\\n\\r\\n\")\n if strategy == \"eager\":\n playbook << OpenConnection(server)\n playbook >> reply(None)\n playbook << SendData(tctx.client, b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")",
" playbook >> DataReceived(tctx.client, b\"CONNECT second-proxy:8080 HTTP/1.1\\r\\n\\r\\n\")\n playbook << layer.NextLayerHook(Placeholder())\n playbook >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n playbook << SendData(tctx.client,\n b\"HTTP/1.1 502 Bad Gateway\\r\\n\"\n b\"content-length: 198\\r\\n\"\n b\"\\r\\n\"\n b\"mitmproxy received an HTTP CONNECT request even though it is not running in regular/upstream mode. \"\n b\"This usually indicates a misconfiguration, please see the mitmproxy mode documentation for details.\")",
" assert playbook",
"\ndef test_no_headers(tctx):\n \"\"\"Test that we can correctly reassemble requests/responses with no headers.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n )\n assert server().address == (\"example.com\", 80)",
"\ndef test_http_proxy_relative_request(tctx):\n \"\"\"Test handling of a relative-form \"GET /\" in regular proxy mode.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n )\n assert server().address == (\"example.com\", 80)",
"\ndef test_http_proxy_relative_request_no_host_header(tctx):\n \"\"\"Test handling of a relative-form \"GET /\" in regular proxy mode, but without a host header.\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"400 Bad Request\" in err()\n assert b\"HTTP request has no host header, destination unknown.\" in err()",
"\ndef test_http_expect(tctx):\n \"\"\"Test handling of a 'Expect: 100-continue' header.\"\"\"\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"PUT http://example.com/large-file HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 15\\r\\n\"\n b\"Expect: 100-continue\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 100 Continue\\r\\n\\r\\n\")\n >> DataReceived(tctx.client, b\"lots of content\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"PUT /large-file HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 15\\r\\n\\r\\n\"\n b\"lots of content\")\n >> DataReceived(server, b\"HTTP/1.1 201 Created\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 201 Created\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )\n assert server().address == (\"example.com\", 80)",
"\n@pytest.mark.parametrize(\"stream\", [True, False])\ndef test_http_client_aborts(tctx, stream):\n \"\"\"Test handling of the case where a client aborts during request transmission.\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=True)",
" def enable_streaming(flow: HTTPFlow):\n flow.request.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n << http.HttpRequestHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_streaming)\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n )\n else:\n assert playbook >> reply()\n (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )\n if stream:\n playbook << CloseConnection(server)\n assert (\n playbook\n << http.HttpErrorHook(flow)\n >> reply()\n << None\n )",
" assert \"peer closed connection\" in flow().error.msg\n assert not flow().live",
"\n@pytest.mark.parametrize(\"stream\", [True, False])\ndef test_http_server_aborts(tctx, stream):\n \"\"\"Test handling of the case where a server aborts during response transmission.\"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))",
" def enable_streaming(flow: HTTPFlow):\n flow.response.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n << http.HttpResponseHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_streaming)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"abc\")\n )\n else:\n assert playbook >> reply()\n assert (\n playbook\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply()\n << CloseConnection(tctx.client)\n )\n else:\n error_html = Placeholder(bytes)\n assert (\n playbook\n >> reply()\n << SendData(tctx.client, error_html)\n << CloseConnection(tctx.client)\n )\n assert b\"502 Bad Gateway\" in error_html()\n assert b\"peer closed connection\" in error_html()",
" assert \"peer closed connection\" in flow().error.msg\n assert not flow().live",
"\n@pytest.mark.parametrize(\"when\", [\"http_connect\", \"requestheaders\", \"request\", \"script-response-responseheaders\",\n \"responseheaders\",\n \"response\", \"error\"])\ndef test_kill_flow(tctx, when):\n \"\"\"Test that we properly kill flows if instructed to do so\"\"\"\n tctx.options.connection_strategy = \"lazy\"\n server = Placeholder(Server)\n connect_flow = Placeholder(HTTPFlow)\n flow = Placeholder(HTTPFlow)",
" def kill(flow: HTTPFlow):\n # Can't use flow.kill() here because that currently still depends on a reply object.\n flow.error = Error(Error.KILLED_MESSAGE)",
" def assert_kill(err_hook: bool = True):\n playbook >> reply(side_effect=kill)\n if err_hook:\n playbook << http.HttpErrorHook(flow)\n playbook >> reply()\n playbook << CloseConnection(tctx.client)\n assert playbook\n if flow():\n assert not flow().live",
" playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n assert (playbook\n >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpConnectHook(connect_flow))\n if when == \"http_connect\":\n return assert_kill(False)\n assert (playbook\n >> reply()\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << layer.NextLayerHook(Placeholder())\n >> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))\n << http.HttpRequestHeadersHook(flow))\n if when == \"requestheaders\":\n return assert_kill()\n assert (playbook\n >> reply()\n << http.HttpRequestHook(flow))\n if when == \"request\":\n return assert_kill()\n if when == \"script-response-responseheaders\":\n assert (playbook\n >> reply(side_effect=lambda f: setattr(f, \"response\", Response.make()))\n << http.HttpResponseHeadersHook(flow))\n return assert_kill()\n assert (playbook\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET /foo?hello=1 HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 12\\r\\n\\r\\nHello World\")\n << http.HttpResponseHeadersHook(flow))\n if when == \"responseheaders\":\n return assert_kill()",
" if when == \"response\":\n assert (playbook\n >> reply()\n >> DataReceived(server, b\"!\")\n << http.HttpResponseHook(flow))\n return assert_kill(False)\n elif when == \"error\":\n assert (playbook\n >> reply()\n >> ConnectionClosed(server)\n << CloseConnection(server)\n << http.HttpErrorHook(flow))\n return assert_kill(False)\n else:\n raise AssertionError",
"\ndef test_close_during_connect_hook(tctx):\n flow = Placeholder(HTTPFlow)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client,\n b'CONNECT hi.ls:443 HTTP/1.1\\r\\n'\n b'Proxy-Connection: keep-alive\\r\\n'\n b'Connection: keep-alive\\r\\n'\n b'Host: hi.ls:443\\r\\n\\r\\n')\n << http.HttpConnectHook(flow)\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n >> reply(to=-3)\n )",
"\n@pytest.mark.parametrize(\"client_close\", [b\"\", b\"Connection: close\\r\\n\"])\n@pytest.mark.parametrize(\"server_close\", [b\"\", b\"Connection: close\\r\\n\"])\ndef test_connection_close_header(tctx, client_close, server_close):\n \"\"\"Test that we correctly close connections if we have a `Connection: close` header.\"\"\"\n if not client_close and not server_close:\n return\n server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example/ HTTP/1.1\\r\\n\"\n b\"Host: example\\r\\n\" + client_close +\n b\"\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example\\r\\n\" + client_close +\n b\"\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\" + server_close +\n b\"\\r\\n\")\n << CloseConnection(server)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\" + server_close +\n b\"\\r\\n\")\n << CloseConnection(tctx.client)\n )",
"\n@pytest.mark.parametrize(\"proto\", [\"websocket\", \"tcp\", \"none\"])\ndef test_upgrade(tctx, proto):\n \"\"\"Test a HTTP -> WebSocket upgrade with different protocols enabled\"\"\"\n if proto != \"websocket\":\n tctx.options.websocket = False\n if proto != \"tcp\":\n tctx.options.rawtcp = False",
" tctx.server.address = (\"example.com\", 80)\n tctx.server.state = ConnectionState.OPEN\n http_flow = Placeholder(HTTPFlow)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.transparent))\n (\n playbook\n >> DataReceived(tctx.client,\n b\"GET / HTTP/1.1\\r\\n\"\n b\"Connection: upgrade\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Sec-WebSocket-Version: 13\\r\\n\"\n b\"\\r\\n\")\n << http.HttpRequestHeadersHook(http_flow)\n >> reply()\n << http.HttpRequestHook(http_flow)\n >> reply()\n << SendData(tctx.server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Connection: upgrade\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Sec-WebSocket-Version: 13\\r\\n\"\n b\"\\r\\n\")\n >> DataReceived(tctx.server, b\"HTTP/1.1 101 Switching Protocols\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Connection: Upgrade\\r\\n\"\n b\"\\r\\n\")\n << http.HttpResponseHeadersHook(http_flow)\n >> reply()\n << http.HttpResponseHook(http_flow)\n >> reply()\n << SendData(tctx.client, b\"HTTP/1.1 101 Switching Protocols\\r\\n\"\n b\"Upgrade: websocket\\r\\n\"\n b\"Connection: Upgrade\\r\\n\"\n b\"\\r\\n\")\n )\n if proto == \"websocket\":\n assert playbook << WebsocketStartHook(http_flow)\n elif proto == \"tcp\":\n assert playbook << TcpStartHook(Placeholder(TCPFlow))\n else:\n assert (\n playbook\n << Log(\"Sent HTTP 101 response, but no protocol is enabled to upgrade to.\", \"warn\")\n << CloseConnection(tctx.client)\n )",
"\ndef test_dont_reuse_closed(tctx):\n \"\"\"Test that a closed connection is not reused.\"\"\"\n server = Placeholder(Server)\n server2 = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n >> ConnectionClosed(server)\n << CloseConnection(server)\n >> DataReceived(tctx.client, b\"GET http://example.com/two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n << OpenConnection(server2)\n >> reply(None)\n << SendData(server2, b\"GET /two HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n\")\n >> DataReceived(server2, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n )",
"\ndef test_reuse_error(tctx):\n \"\"\"Test that an errored connection is reused.\"\"\"\n tctx.server.address = (\"example.com\", 443)\n tctx.server.error = \"tls verify failed\"\n error_html = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent), hooks=False)\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n << SendData(tctx.client, error_html)\n << CloseConnection(tctx.client)\n )\n assert b\"502 Bad Gateway\" in error_html()\n assert b\"tls verify failed\" in error_html()",
"\ndef test_transparent_sni(tctx):\n \"\"\"Test that we keep the SNI in lazy transparent mode.\"\"\"\n tctx.client.sni = \"example.com\"\n tctx.server.address = (\"192.0.2.42\", 443)\n tctx.server.tls = True",
" flow = Placeholder(HTTPFlow)",
" server = Placeholder(Server)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent))\n >> DataReceived(tctx.client, b\"GET / HTTP/1.1\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n )\n assert server().address == (\"192.0.2.42\", 443)\n assert server().sni == \"example.com\"",
"\ndef test_original_server_disconnects(tctx):\n \"\"\"Test that we correctly handle the case where the initial server conn is just closed.\"\"\"\n tctx.server.state = ConnectionState.OPEN\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.transparent))\n >> ConnectionClosed(tctx.server)\n << CloseConnection(tctx.server)\n )",
"\ndef test_request_smuggling(tctx):\n \"\"\"Test that we reject request smuggling\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 42\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\")\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Received both a Transfer-Encoding and a Content-Length header\" in err()",
"",
"def test_request_smuggling_whitespace(tctx):\n \"\"\"Test that we reject header names with whitespace\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length : 42\\r\\n\\r\\n\")\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Received an invalid header name\" in err()",
"\ndef test_request_smuggling_validation_disabled(tctx):\n \"\"\"Test that we don't reject request smuggling when validation is disabled.\"\"\"\n tctx.options.validate_inbound_headers = False\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, b\"GET http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 4\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"4\\r\\n\"\n b\"abcd\\r\\n\"\n b\"0\\r\\n\"\n b\"\\r\\n\")\n << OpenConnection(Placeholder(Server))\n )",
"",
"def test_request_smuggling_te_te(tctx):\n \"\"\"Test that we reject transfer-encoding headers that are weird in some way\"\"\"\n err = Placeholder(bytes)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)\n >> DataReceived(tctx.client, (\"GET http://example.com/ HTTP/1.1\\r\\n\"\n \"Host: example.com\\r\\n\"\n \"Transfer-Encoding: chunKed\\r\\n\\r\\n\").encode()) # note the non-standard \"K\"\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Invalid transfer encoding\" in err()",
"\ndef test_invalid_content_length(tctx):\n \"\"\"Test that we still trigger flow hooks for requests with semantic errors\"\"\"\n err = Placeholder(bytes)\n flow = Placeholder(HTTPFlow)\n assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, (\"GET http://example.com/ HTTP/1.1\\r\\n\"\n \"Host: example.com\\r\\n\"\n \"Content-Length: NaN\\r\\n\\r\\n\").encode())\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpErrorHook(flow)\n >> reply()\n )\n assert b\"Invalid Content-Length header\" in err()",
"\ndef test_chunked_and_content_length_set_by_addon(tctx):\n \"\"\"Test that we don't crash when an addon sets a transfer-encoding header",
" We reject a request with both transfer-encoding and content-length header to\n thwart request smuggling, but if a user explicitly sets it we should not crash.\n \"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)",
" def make_chunked(flow: HTTPFlow):\n if flow.response:\n flow.response.headers[\"Transfer-Encoding\"] = \"chunked\"\n else:\n flow.request.headers[\"Transfer-Encoding\"] = \"chunked\"",
" assert (\n Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n >> DataReceived(tctx.client, b\"POST http://example.com/ HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 0\\r\\n\\r\\n\")\n << http.HttpRequestHeadersHook(flow)\n >> reply(side_effect=make_chunked)\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"POST / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\"\n b\"Content-Length: 0\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 0\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply(side_effect=make_chunked)\n << SendData(tctx.client, b\"HTTP/1.1 200 OK\\r\\n\"\n b\"Content-Length: 0\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\\r\\n\"\n b\"0\\r\\n\\r\\n\")\n )",
"\ndef test_connect_more_newlines(tctx):\n \"\"\"Ignore superfluous \\r\\n in CONNECT request, https://github.com/mitmproxy/mitmproxy/issues/4870\"\"\"\n server = Placeholder(Server)\n playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n nl = Placeholder(layer.NextLayer)",
" assert (\n playbook\n >> DataReceived(tctx.client, b\"CONNECT example.com:80 HTTP/1.1\\r\\n\\r\\n\\r\\n\")\n << http.HttpConnectHook(Placeholder())\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(tctx.client, b'HTTP/1.1 200 Connection established\\r\\n\\r\\n')\n >> DataReceived(tctx.client, b\"\\x16\\x03\\x03\\x00\\xb3\\x01\\x00\\x00\\xaf\\x03\\x03\")\n << layer.NextLayerHook(nl)\n )\n assert nl().data_client() == b\"\\x16\\x03\\x03\\x00\\xb3\\x01\\x00\\x00\\xaf\\x03\\x03\""
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"from typing import List, Tuple",
"import h2.settings\nimport hpack\nimport hyperframe.frame\nimport pytest\nfrom h2.errors import ErrorCodes",
"from mitmproxy.connection import ConnectionState, Server\nfrom mitmproxy.flow import Error\nfrom mitmproxy.http import HTTPFlow, Headers, Request\nfrom mitmproxy.net.http import status_codes\nfrom mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData\nfrom mitmproxy.proxy.context import Context\nfrom mitmproxy.proxy.events import ConnectionClosed, DataReceived\nfrom mitmproxy.proxy.layers import http\nfrom mitmproxy.proxy.layers.http import HTTPMode\nfrom mitmproxy.proxy.layers.http._http2 import Http2Client, split_pseudo_headers\nfrom test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory\nfrom test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply",
"example_request_headers = (\n (b':method', b'GET'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n)",
"example_response_headers = (\n (b':status', b'200'),\n)",
"example_request_trailers = (\n (b'req-trailer-a', b'a'),\n (b'req-trailer-b', b'b')\n)",
"example_response_trailers = (\n (b'resp-trailer-a', b'a'),\n (b'resp-trailer-b', b'b')\n)",
"\n@pytest.fixture\ndef open_h2_server_conn():\n # this is a bit fake here (port 80, with alpn, but no tls - c'mon),\n # but we don't want to pollute our tests with TLS handshakes.\n s = Server((\"example.com\", 80))\n s.state = ConnectionState.OPEN\n s.alpn = b\"h2\"\n return s",
"\ndef decode_frames(data: bytes) -> List[hyperframe.frame.Frame]:\n # swallow preamble\n if data.startswith(b\"PRI * HTTP/2.0\"):\n data = data[24:]\n frames = []\n while data:\n f, length = hyperframe.frame.Frame.parse_frame_header(data[:9])\n f.parse_body(memoryview(data[9:9 + length]))\n frames.append(f)\n data = data[9 + length:]\n return frames",
"\ndef start_h2_client(tctx: Context) -> Tuple[Playbook, FrameFactory]:\n tctx.client.alpn = b\"h2\"\n frame_factory = FrameFactory()",
" playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n assert (\n playbook\n << SendData(tctx.client, Placeholder()) # initial settings frame\n >> DataReceived(tctx.client, frame_factory.preamble())\n >> DataReceived(tctx.client, frame_factory.build_settings_frame({}, ack=True).serialize())\n )\n return playbook, frame_factory",
"\ndef make_h2(open_connection: OpenConnection) -> None:\n open_connection.connection.alpn = b\"h2\"",
"\ndef test_simple(tctx):\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)\n initial = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, initial)\n )\n frames = decode_frames(initial())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n sff = FrameFactory()\n assert (\n playbook\n # a conforming h2 server would send settings first, we disregard this for now.\n >> DataReceived(server, sff.build_headers_frame(example_response_headers).serialize())\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n >> DataReceived(server, sff.build_data_frame(b\"Hello, World!\", flags=[\"END_STREAM\"]).serialize())\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client,\n cff.build_headers_frame(example_response_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize() +\n cff.build_data_frame(b\"\", flags=[\"END_STREAM\"]).serialize())\n )\n assert flow().request.url == \"http://example.com/\"\n assert flow().response.text == \"Hello, World!\"",
"\n@pytest.mark.parametrize(\"stream\", [\"stream\", \"\"])\ndef test_response_trailers(tctx: Context, open_h2_server_conn: Server, stream):\n playbook, cff = start_h2_client(tctx)\n tctx.server = open_h2_server_conn\n sff = FrameFactory()",
" def enable_streaming(flow: HTTPFlow):\n flow.response.stream = bool(stream)",
" flow = Placeholder(HTTPFlow)\n (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << SendData(tctx.server, Placeholder(bytes))\n # a conforming h2 server would send settings first, we disregard this for now.\n >> DataReceived(tctx.server, sff.build_headers_frame(example_response_headers).serialize() +\n sff.build_data_frame(b\"Hello, World!\").serialize())\n << http.HttpResponseHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n )\n if stream:\n playbook << SendData(\n tctx.client,\n cff.build_headers_frame(example_response_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize()\n )\n assert (\n playbook\n >> DataReceived(tctx.server, sff.build_headers_frame(example_response_trailers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpResponseHook(flow)\n )\n assert flow().response.trailers\n del flow().response.trailers[\"resp-trailer-a\"]\n if stream:\n assert (\n playbook\n >> reply()\n << SendData(tctx.client,\n cff.build_headers_frame(example_response_trailers[1:], flags=[\"END_STREAM\"]).serialize())\n )\n else:\n assert (\n playbook\n >> reply()\n << SendData(tctx.client,\n cff.build_headers_frame(example_response_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize() +\n cff.build_headers_frame(example_response_trailers[1:], flags=[\"END_STREAM\"]).serialize()))",
"\n@pytest.mark.parametrize(\"stream\", [\"stream\", \"\"])\ndef test_request_trailers(tctx: Context, open_h2_server_conn: Server, stream):\n playbook, cff = start_h2_client(tctx)\n tctx.server = open_h2_server_conn",
" def enable_streaming(flow: HTTPFlow):\n flow.request.stream = bool(stream)",
" flow = Placeholder(HTTPFlow)\n server_data1 = Placeholder(bytes)\n server_data2 = Placeholder(bytes)\n (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize()\n )\n << http.HttpRequestHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n )\n if stream:\n playbook << SendData(tctx.server, server_data1)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_trailers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHook(flow)\n >> reply()\n << SendData(tctx.server, server_data2)\n )\n frames = decode_frames(server_data1.setdefault(b\"\") + server_data2())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n hyperframe.frame.DataFrame,\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_upstream_error(tctx):\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)\n err = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(\"oops server <> error\")\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n )\n frames = decode_frames(err())\n assert [type(x) for x in frames] == [\n hyperframe.frame.HeadersFrame,\n hyperframe.frame.DataFrame,\n ]\n d = frames[1]\n assert isinstance(d, hyperframe.frame.DataFrame)\n assert b\"502 Bad Gateway\" in d.data\n assert b\"server <> error\" in d.data",
"\n@pytest.mark.parametrize(\"stream\", [\"stream\", \"\"])\n@pytest.mark.parametrize(\"when\", [\"request\", \"response\"])\n@pytest.mark.parametrize(\"how\", [\"RST\", \"disconnect\", \"RST+disconnect\"])\ndef test_http2_client_aborts(tctx, stream, when, how):\n \"\"\"\n Test handling of the case where a client aborts during request or response transmission.",
" If the client aborts the request transmission, we must trigger an error hook,\n if the client disconnects during response transmission, no error hook is triggered.\n \"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook, cff = start_h2_client(tctx)\n resp = Placeholder(bytes)",
" def enable_request_streaming(flow: HTTPFlow):\n flow.request.stream = True",
" def enable_response_streaming(flow: HTTPFlow):\n flow.response.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, cff.build_headers_frame(example_request_headers).serialize())\n << http.HttpRequestHeadersHook(flow)\n )\n if stream and when == \"request\":\n assert (\n playbook\n >> reply(side_effect=enable_request_streaming)\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n )\n else:\n assert playbook >> reply()",
" if when == \"request\":\n if \"RST\" in how:\n playbook >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n else:\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)",
" if stream:\n playbook << CloseConnection(server)\n playbook << http.HttpErrorHook(flow)\n playbook >> reply()",
" if how == \"RST+disconnect\":\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)",
" assert playbook\n assert \"stream reset\" in flow().error.msg or \"peer closed connection\" in flow().error.msg\n return",
" assert (\n playbook\n >> DataReceived(tctx.client, cff.build_data_frame(b\"\", flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\n\\r\\n123\")\n << http.HttpResponseHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_response_streaming)\n << SendData(tctx.client, resp)\n )\n else:\n assert playbook >> reply()",
" if \"RST\" in how:\n playbook >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n else:\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)",
" assert (\n playbook\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n )",
" if how == \"RST+disconnect\":\n assert (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )",
" if \"RST\" in how:\n assert \"stream reset\" in flow().error.msg\n else:\n assert \"peer closed connection\" in flow().error.msg",
"",
"@pytest.mark.xfail(reason=\"inbound validation turned on to protect against request smuggling\")",
"@pytest.mark.parametrize(\"normalize\", [True, False])\ndef test_no_normalization(tctx, normalize):\n \"\"\"Test that we don't normalize headers when we just pass them through.\"\"\"\n tctx.options.normalize_outbound_headers = normalize",
"",
"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook, cff = start_h2_client(tctx)",
" request_headers = list(example_request_headers) + [(b\"Should-Not-Be-Capitalized! \", b\" :) \")]\n request_headers_lower = [(k.lower(), v) for (k, v) in request_headers]\n response_headers = list(example_response_headers) + [(b\"Same\", b\"Here\")]\n response_headers_lower = [(k.lower(), v) for (k, v) in response_headers]",
" initial = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, initial)\n )\n frames = decode_frames(initial())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n assert hpack.hpack.Decoder().decode(frames[1].data, True) == request_headers_lower if normalize else request_headers",
" sff = FrameFactory()\n (\n playbook\n >> DataReceived(server, sff.build_headers_frame(response_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n )\n if normalize:\n playbook << Log(\"Lowercased 'Same' header as uppercase is not allowed with HTTP/2.\")\n hdrs = response_headers_lower if normalize else response_headers\n assert playbook << SendData(tctx.client, cff.build_headers_frame(hdrs, flags=[\"END_STREAM\"]).serialize())",
" assert flow().request.headers.fields == ((b\"Should-Not-Be-Capitalized! \", b\" :) \"),)\n assert flow().response.headers.fields == ((b\"Same\", b\"Here\"),)",
"\n@pytest.mark.parametrize(\"input,pseudo,headers\", [\n ([(b\"foo\", b\"bar\")], {}, {\"foo\": \"bar\"}),\n ([(b\":status\", b\"418\")], {b\":status\": b\"418\"}, {}),\n ([(b\":status\", b\"418\"), (b\"foo\", b\"bar\")], {b\":status\": b\"418\"}, {\"foo\": \"bar\"}),\n])\ndef test_split_pseudo_headers(input, pseudo, headers):\n actual_pseudo, actual_headers = split_pseudo_headers(input)\n assert pseudo == actual_pseudo\n assert Headers(**headers) == actual_headers",
"\ndef test_split_pseudo_headers_err():\n with pytest.raises(ValueError, match=\"Duplicate HTTP/2 pseudo header\"):\n split_pseudo_headers([(b\":status\", b\"418\"), (b\":status\", b\"418\")])",
"\ndef test_rst_then_close(tctx):\n \"\"\"\n Test that we properly handle the case of a client that first causes protocol errors and then disconnects.",
" Adapted from h2spec http2/5.1/5.\n \"\"\"\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> DataReceived(tctx.client, cff.build_data_frame(b\"unexpected data frame\").serialize())\n << SendData(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.STREAM_CLOSED).serialize())\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n >> reply(\"connection cancelled\", to=-5)\n << http.HttpErrorHook(flow)\n >> reply()\n )\n assert flow().error.msg == \"connection cancelled\"",
"\ndef test_cancel_then_server_disconnect(tctx):\n \"\"\"\n Test that we properly handle the case of the following event sequence:\n - client cancels a stream\n - we start an error hook\n - server disconnects\n - error hook completes.\n \"\"\"\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n')\n >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n >> ConnectionClosed(server)\n << None\n )",
"\ndef test_cancel_during_response_hook(tctx):\n \"\"\"\n Test that we properly handle the case of the following event sequence:\n - we receive a server response\n - we trigger the response hook\n - the client cancels the stream\n - the response hook completes",
" Given that we have already triggered the response hook, we don't want to trigger the error hook.\n \"\"\"\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n')\n >> DataReceived(server, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n << CloseConnection(server)\n >> reply(to=-2)\n << http.HttpResponseHook(flow)\n >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n >> reply(to=-2)\n )",
"\ndef test_stream_concurrency(tctx):\n \"\"\"Test that we can send an intercepted request with a lower stream id than one that has already been sent.\"\"\"\n playbook, cff = start_h2_client(tctx)\n flow1 = Placeholder(HTTPFlow)\n flow2 = Placeholder(HTTPFlow)",
" reqheadershook1 = http.HttpRequestHeadersHook(flow1)\n reqheadershook2 = http.HttpRequestHeadersHook(flow2)\n reqhook1 = http.HttpRequestHook(flow1)\n reqhook2 = http.HttpRequestHook(flow2)",
" server = Placeholder(Server)\n data_req1 = Placeholder(bytes)\n data_req2 = Placeholder(bytes)",
" assert (playbook\n >> DataReceived(\n tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=1).serialize() +\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=3).serialize())\n << reqheadershook1\n << reqheadershook2\n >> reply(to=reqheadershook1)\n << reqhook1\n >> reply(to=reqheadershook2)\n << reqhook2\n # req 2 overtakes 1 and we already have a reply:\n >> reply(to=reqhook2)\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, data_req2)\n >> reply(to=reqhook1)\n << SendData(server, data_req1)\n )\n frames = decode_frames(data_req2())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n frames = decode_frames(data_req1())\n assert [type(x) for x in frames] == [\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_max_concurrency(tctx):\n playbook, cff = start_h2_client(tctx)\n server = Placeholder(Server)\n req1_bytes = Placeholder(bytes)\n settings_ack_bytes = Placeholder(bytes)\n req2_bytes = Placeholder(bytes)\n playbook.hooks = False\n sff = FrameFactory()",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"],\n stream_id=1).serialize())\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, req1_bytes)\n >> DataReceived(server,\n sff.build_settings_frame(\n {h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 1}).serialize())\n << SendData(server, settings_ack_bytes)\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers,\n flags=[\"END_STREAM\"],\n stream_id=3).serialize())\n # Can't send it upstream yet, all streams in use!\n >> DataReceived(server, sff.build_headers_frame(example_response_headers,\n flags=[\"END_STREAM\"],\n stream_id=1).serialize())\n # But now we can!\n << SendData(server, req2_bytes)\n << SendData(tctx.client, Placeholder(bytes))\n >> DataReceived(server, sff.build_headers_frame(example_response_headers,\n flags=[\"END_STREAM\"],\n stream_id=3).serialize())\n << SendData(tctx.client, Placeholder(bytes))\n )\n settings, req1 = decode_frames(req1_bytes())\n settings_ack, = decode_frames(settings_ack_bytes())\n req2, = decode_frames(req2_bytes())",
" assert type(settings) == hyperframe.frame.SettingsFrame\n assert type(req1) == hyperframe.frame.HeadersFrame\n assert type(settings_ack) == hyperframe.frame.SettingsFrame\n assert type(req2) == hyperframe.frame.HeadersFrame\n assert req1.stream_id == 1\n assert req2.stream_id == 3",
"\ndef test_stream_concurrent_get_connection(tctx):\n \"\"\"Test that an immediate second request for the same domain does not trigger a second connection attempt.\"\"\"\n playbook, cff = start_h2_client(tctx)\n playbook.hooks = False",
" server = Placeholder(Server)\n data = Placeholder(bytes)",
" assert (playbook\n >> DataReceived(tctx.client, cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"],\n stream_id=1).serialize())\n << (o := OpenConnection(server))\n >> DataReceived(tctx.client, cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"],\n stream_id=3).serialize())\n >> reply(None, to=o, side_effect=make_h2)\n << SendData(server, data)\n )\n frames = decode_frames(data())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_kill_stream(tctx):\n \"\"\"Test that we can kill individual streams.\"\"\"\n playbook, cff = start_h2_client(tctx)\n flow1 = Placeholder(HTTPFlow)\n flow2 = Placeholder(HTTPFlow)",
" req_headers_hook_1 = http.HttpRequestHeadersHook(flow1)",
" def kill(flow: HTTPFlow):\n # Can't use flow.kill() here because that currently still depends on a reply object.\n flow.error = Error(Error.KILLED_MESSAGE)",
" server = Placeholder(Server)\n data_req1 = Placeholder(bytes)",
" assert (playbook\n >> DataReceived(\n tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=1).serialize() +\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=3).serialize())\n << req_headers_hook_1\n << http.HttpRequestHeadersHook(flow2)\n >> reply(side_effect=kill)\n << http.HttpErrorHook(flow2)\n >> reply()\n << SendData(tctx.client, cff.build_rst_stream_frame(3, error_code=ErrorCodes.INTERNAL_ERROR).serialize())\n >> reply(to=req_headers_hook_1)\n << http.HttpRequestHook(flow1)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, data_req1)\n )\n frames = decode_frames(data_req1())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]",
"\nclass TestClient:\n def test_no_data_on_closed_stream(self, tctx):\n frame_factory = FrameFactory()\n req = Request.make(\"GET\", \"http://example.com/\")\n resp = {\n \":status\": 200\n }\n assert (\n Playbook(Http2Client(tctx))\n << SendData(tctx.server, Placeholder(bytes)) # preamble + initial settings frame\n >> DataReceived(tctx.server, frame_factory.build_settings_frame({}, ack=True).serialize())\n >> http.RequestHeaders(1, req, end_stream=True)\n << SendData(tctx.server, b\"\\x00\\x00\\x06\\x01\\x05\\x00\\x00\\x00\\x01\\x82\\x86\\x84\\\\\\x81\\x07\")\n >> http.RequestEndOfMessage(1)\n >> DataReceived(tctx.server, frame_factory.build_headers_frame(resp).serialize())\n << http.ReceiveHttp(Placeholder(http.ResponseHeaders))\n >> http.RequestProtocolError(1, \"cancelled\", code=status_codes.CLIENT_CLOSED_REQUEST)\n << SendData(tctx.server, frame_factory.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n >> DataReceived(tctx.server, frame_factory.build_data_frame(b\"foo\").serialize())\n << SendData(tctx.server, frame_factory.build_rst_stream_frame(1, ErrorCodes.STREAM_CLOSED).serialize())\n ) # important: no ResponseData event here!",
"\ndef test_early_server_data(tctx):\n playbook, cff = start_h2_client(tctx)\n sff = FrameFactory()",
" tctx.server.address = (\"example.com\", 80)\n tctx.server.state = ConnectionState.OPEN\n tctx.server.alpn = b\"h2\"",
" flow = Placeholder(HTTPFlow)\n server1 = Placeholder(bytes)\n server2 = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << (h := http.HttpRequestHook(flow))\n # Surprise! We get data from the server before the request hook finishes.\n >> DataReceived(tctx.server, sff.build_settings_frame({}).serialize())\n << SendData(tctx.server, server1)\n # Request hook finishes...\n >> reply(to=h)\n << SendData(tctx.server, server2)\n )\n assert [type(x) for x in decode_frames(server1())] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.SettingsFrame,\n ]\n assert [type(x) for x in decode_frames(server2())] == [\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_request_smuggling_cl(tctx):\n playbook, cff = start_h2_client(tctx)\n playbook.hooks = False\n err = Placeholder(bytes)",
" headers = (\n (b':method', b'POST'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n (b'content-length', b'3')\n )",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(headers).serialize())\n >> DataReceived(tctx.client,\n cff.build_data_frame(b\"abcPOST / HTTP/1.1 ...\", flags=[\"END_STREAM\"]).serialize())\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"InvalidBodyLengthError\" in err()",
"\ndef test_request_smuggling_te(tctx):\n playbook, cff = start_h2_client(tctx)\n playbook.hooks = False\n err = Placeholder(bytes)",
" headers = (\n (b':method', b'POST'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n (b'transfer-encoding', b'chunked')\n )",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(headers, flags=[\"END_STREAM\"]).serialize())\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Connection-specific header field present\" in err()"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"from typing import List, Tuple",
"import h2.settings\nimport hpack\nimport hyperframe.frame\nimport pytest\nfrom h2.errors import ErrorCodes",
"from mitmproxy.connection import ConnectionState, Server\nfrom mitmproxy.flow import Error\nfrom mitmproxy.http import HTTPFlow, Headers, Request\nfrom mitmproxy.net.http import status_codes\nfrom mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData\nfrom mitmproxy.proxy.context import Context\nfrom mitmproxy.proxy.events import ConnectionClosed, DataReceived\nfrom mitmproxy.proxy.layers import http\nfrom mitmproxy.proxy.layers.http import HTTPMode\nfrom mitmproxy.proxy.layers.http._http2 import Http2Client, split_pseudo_headers\nfrom test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory\nfrom test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply",
"example_request_headers = (\n (b':method', b'GET'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n)",
"example_response_headers = (\n (b':status', b'200'),\n)",
"example_request_trailers = (\n (b'req-trailer-a', b'a'),\n (b'req-trailer-b', b'b')\n)",
"example_response_trailers = (\n (b'resp-trailer-a', b'a'),\n (b'resp-trailer-b', b'b')\n)",
"\n@pytest.fixture\ndef open_h2_server_conn():\n # this is a bit fake here (port 80, with alpn, but no tls - c'mon),\n # but we don't want to pollute our tests with TLS handshakes.\n s = Server((\"example.com\", 80))\n s.state = ConnectionState.OPEN\n s.alpn = b\"h2\"\n return s",
"\ndef decode_frames(data: bytes) -> List[hyperframe.frame.Frame]:\n # swallow preamble\n if data.startswith(b\"PRI * HTTP/2.0\"):\n data = data[24:]\n frames = []\n while data:\n f, length = hyperframe.frame.Frame.parse_frame_header(data[:9])\n f.parse_body(memoryview(data[9:9 + length]))\n frames.append(f)\n data = data[9 + length:]\n return frames",
"\ndef start_h2_client(tctx: Context) -> Tuple[Playbook, FrameFactory]:\n tctx.client.alpn = b\"h2\"\n frame_factory = FrameFactory()",
" playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))\n assert (\n playbook\n << SendData(tctx.client, Placeholder()) # initial settings frame\n >> DataReceived(tctx.client, frame_factory.preamble())\n >> DataReceived(tctx.client, frame_factory.build_settings_frame({}, ack=True).serialize())\n )\n return playbook, frame_factory",
"\ndef make_h2(open_connection: OpenConnection) -> None:\n open_connection.connection.alpn = b\"h2\"",
"\ndef test_simple(tctx):\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)\n initial = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, initial)\n )\n frames = decode_frames(initial())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n sff = FrameFactory()\n assert (\n playbook\n # a conforming h2 server would send settings first, we disregard this for now.\n >> DataReceived(server, sff.build_headers_frame(example_response_headers).serialize())\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n >> DataReceived(server, sff.build_data_frame(b\"Hello, World!\", flags=[\"END_STREAM\"]).serialize())\n << http.HttpResponseHook(flow)\n >> reply()\n << SendData(tctx.client,\n cff.build_headers_frame(example_response_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize() +\n cff.build_data_frame(b\"\", flags=[\"END_STREAM\"]).serialize())\n )\n assert flow().request.url == \"http://example.com/\"\n assert flow().response.text == \"Hello, World!\"",
"\n@pytest.mark.parametrize(\"stream\", [\"stream\", \"\"])\ndef test_response_trailers(tctx: Context, open_h2_server_conn: Server, stream):\n playbook, cff = start_h2_client(tctx)\n tctx.server = open_h2_server_conn\n sff = FrameFactory()",
" def enable_streaming(flow: HTTPFlow):\n flow.response.stream = bool(stream)",
" flow = Placeholder(HTTPFlow)\n (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << SendData(tctx.server, Placeholder(bytes))\n # a conforming h2 server would send settings first, we disregard this for now.\n >> DataReceived(tctx.server, sff.build_headers_frame(example_response_headers).serialize() +\n sff.build_data_frame(b\"Hello, World!\").serialize())\n << http.HttpResponseHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n )\n if stream:\n playbook << SendData(\n tctx.client,\n cff.build_headers_frame(example_response_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize()\n )\n assert (\n playbook\n >> DataReceived(tctx.server, sff.build_headers_frame(example_response_trailers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpResponseHook(flow)\n )\n assert flow().response.trailers\n del flow().response.trailers[\"resp-trailer-a\"]\n if stream:\n assert (\n playbook\n >> reply()\n << SendData(tctx.client,\n cff.build_headers_frame(example_response_trailers[1:], flags=[\"END_STREAM\"]).serialize())\n )\n else:\n assert (\n playbook\n >> reply()\n << SendData(tctx.client,\n cff.build_headers_frame(example_response_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize() +\n cff.build_headers_frame(example_response_trailers[1:], flags=[\"END_STREAM\"]).serialize()))",
"\n@pytest.mark.parametrize(\"stream\", [\"stream\", \"\"])\ndef test_request_trailers(tctx: Context, open_h2_server_conn: Server, stream):\n playbook, cff = start_h2_client(tctx)\n tctx.server = open_h2_server_conn",
" def enable_streaming(flow: HTTPFlow):\n flow.request.stream = bool(stream)",
" flow = Placeholder(HTTPFlow)\n server_data1 = Placeholder(bytes)\n server_data2 = Placeholder(bytes)\n (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers).serialize() +\n cff.build_data_frame(b\"Hello, World!\").serialize()\n )\n << http.HttpRequestHeadersHook(flow)\n >> reply(side_effect=enable_streaming)\n )\n if stream:\n playbook << SendData(tctx.server, server_data1)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_trailers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHook(flow)\n >> reply()\n << SendData(tctx.server, server_data2)\n )\n frames = decode_frames(server_data1.setdefault(b\"\") + server_data2())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n hyperframe.frame.DataFrame,\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_upstream_error(tctx):\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)\n err = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(\"oops server <> error\")\n << http.HttpErrorHook(flow)\n >> reply()\n << SendData(tctx.client, err)\n )\n frames = decode_frames(err())\n assert [type(x) for x in frames] == [\n hyperframe.frame.HeadersFrame,\n hyperframe.frame.DataFrame,\n ]\n d = frames[1]\n assert isinstance(d, hyperframe.frame.DataFrame)\n assert b\"502 Bad Gateway\" in d.data\n assert b\"server <> error\" in d.data",
"\n@pytest.mark.parametrize(\"stream\", [\"stream\", \"\"])\n@pytest.mark.parametrize(\"when\", [\"request\", \"response\"])\n@pytest.mark.parametrize(\"how\", [\"RST\", \"disconnect\", \"RST+disconnect\"])\ndef test_http2_client_aborts(tctx, stream, when, how):\n \"\"\"\n Test handling of the case where a client aborts during request or response transmission.",
" If the client aborts the request transmission, we must trigger an error hook,\n if the client disconnects during response transmission, no error hook is triggered.\n \"\"\"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook, cff = start_h2_client(tctx)\n resp = Placeholder(bytes)",
" def enable_request_streaming(flow: HTTPFlow):\n flow.request.stream = True",
" def enable_response_streaming(flow: HTTPFlow):\n flow.response.stream = True",
" assert (\n playbook\n >> DataReceived(tctx.client, cff.build_headers_frame(example_request_headers).serialize())\n << http.HttpRequestHeadersHook(flow)\n )\n if stream and when == \"request\":\n assert (\n playbook\n >> reply(side_effect=enable_request_streaming)\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n )\n else:\n assert playbook >> reply()",
" if when == \"request\":\n if \"RST\" in how:\n playbook >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n else:\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)",
" if stream:\n playbook << CloseConnection(server)\n playbook << http.HttpErrorHook(flow)\n playbook >> reply()",
" if how == \"RST+disconnect\":\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)",
" assert playbook\n assert \"stream reset\" in flow().error.msg or \"peer closed connection\" in flow().error.msg\n return",
" assert (\n playbook\n >> DataReceived(tctx.client, cff.build_data_frame(b\"\", flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b\"GET / HTTP/1.1\\r\\n\"\n b\"Host: example.com\\r\\n\\r\\n\")\n >> DataReceived(server, b\"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\n\\r\\n123\")\n << http.HttpResponseHeadersHook(flow)\n )\n if stream:\n assert (\n playbook\n >> reply(side_effect=enable_response_streaming)\n << SendData(tctx.client, resp)\n )\n else:\n assert playbook >> reply()",
" if \"RST\" in how:\n playbook >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n else:\n playbook >> ConnectionClosed(tctx.client)\n playbook << CloseConnection(tctx.client)",
" assert (\n playbook\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n )",
" if how == \"RST+disconnect\":\n assert (\n playbook\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n )",
" if \"RST\" in how:\n assert \"stream reset\" in flow().error.msg\n else:\n assert \"peer closed connection\" in flow().error.msg",
"",
"",
"@pytest.mark.parametrize(\"normalize\", [True, False])\ndef test_no_normalization(tctx, normalize):\n \"\"\"Test that we don't normalize headers when we just pass them through.\"\"\"\n tctx.options.normalize_outbound_headers = normalize",
" tctx.options.validate_inbound_headers = False",
"\n server = Placeholder(Server)\n flow = Placeholder(HTTPFlow)\n playbook, cff = start_h2_client(tctx)",
" request_headers = list(example_request_headers) + [(b\"Should-Not-Be-Capitalized! \", b\" :) \")]\n request_headers_lower = [(k.lower(), v) for (k, v) in request_headers]\n response_headers = list(example_response_headers) + [(b\"Same\", b\"Here\")]\n response_headers_lower = [(k.lower(), v) for (k, v) in response_headers]",
" initial = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, initial)\n )\n frames = decode_frames(initial())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n assert hpack.hpack.Decoder().decode(frames[1].data, True) == request_headers_lower if normalize else request_headers",
" sff = FrameFactory()\n (\n playbook\n >> DataReceived(server, sff.build_headers_frame(response_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpResponseHeadersHook(flow)\n >> reply()\n << http.HttpResponseHook(flow)\n >> reply()\n )\n if normalize:\n playbook << Log(\"Lowercased 'Same' header as uppercase is not allowed with HTTP/2.\")\n hdrs = response_headers_lower if normalize else response_headers\n assert playbook << SendData(tctx.client, cff.build_headers_frame(hdrs, flags=[\"END_STREAM\"]).serialize())",
" assert flow().request.headers.fields == ((b\"Should-Not-Be-Capitalized! \", b\" :) \"),)\n assert flow().response.headers.fields == ((b\"Same\", b\"Here\"),)",
"\n@pytest.mark.parametrize(\"input,pseudo,headers\", [\n ([(b\"foo\", b\"bar\")], {}, {\"foo\": \"bar\"}),\n ([(b\":status\", b\"418\")], {b\":status\": b\"418\"}, {}),\n ([(b\":status\", b\"418\"), (b\"foo\", b\"bar\")], {b\":status\": b\"418\"}, {\"foo\": \"bar\"}),\n])\ndef test_split_pseudo_headers(input, pseudo, headers):\n actual_pseudo, actual_headers = split_pseudo_headers(input)\n assert pseudo == actual_pseudo\n assert Headers(**headers) == actual_headers",
"\ndef test_split_pseudo_headers_err():\n with pytest.raises(ValueError, match=\"Duplicate HTTP/2 pseudo header\"):\n split_pseudo_headers([(b\":status\", b\"418\"), (b\":status\", b\"418\")])",
"\ndef test_rst_then_close(tctx):\n \"\"\"\n Test that we properly handle the case of a client that first causes protocol errors and then disconnects.",
" Adapted from h2spec http2/5.1/5.\n \"\"\"\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> DataReceived(tctx.client, cff.build_data_frame(b\"unexpected data frame\").serialize())\n << SendData(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.STREAM_CLOSED).serialize())\n >> ConnectionClosed(tctx.client)\n << CloseConnection(tctx.client)\n >> reply(\"connection cancelled\", to=-5)\n << http.HttpErrorHook(flow)\n >> reply()\n )\n assert flow().error.msg == \"connection cancelled\"",
"\ndef test_cancel_then_server_disconnect(tctx):\n \"\"\"\n Test that we properly handle the case of the following event sequence:\n - client cancels a stream\n - we start an error hook\n - server disconnects\n - error hook completes.\n \"\"\"\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n')\n >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n << CloseConnection(server)\n << http.HttpErrorHook(flow)\n >> reply()\n >> ConnectionClosed(server)\n << None\n )",
"\ndef test_cancel_during_response_hook(tctx):\n \"\"\"\n Test that we properly handle the case of the following event sequence:\n - we receive a server response\n - we trigger the response hook\n - the client cancels the stream\n - the response hook completes",
" Given that we have already triggered the response hook, we don't want to trigger the error hook.\n \"\"\"\n playbook, cff = start_h2_client(tctx)\n flow = Placeholder(HTTPFlow)\n server = Placeholder(Server)",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << http.HttpRequestHook(flow)\n >> reply()\n << OpenConnection(server)\n >> reply(None)\n << SendData(server, b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n')\n >> DataReceived(server, b\"HTTP/1.1 204 No Content\\r\\n\\r\\n\")\n << http.HttpResponseHeadersHook(flow)\n << CloseConnection(server)\n >> reply(to=-2)\n << http.HttpResponseHook(flow)\n >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n >> reply(to=-2)\n )",
"\ndef test_stream_concurrency(tctx):\n \"\"\"Test that we can send an intercepted request with a lower stream id than one that has already been sent.\"\"\"\n playbook, cff = start_h2_client(tctx)\n flow1 = Placeholder(HTTPFlow)\n flow2 = Placeholder(HTTPFlow)",
" reqheadershook1 = http.HttpRequestHeadersHook(flow1)\n reqheadershook2 = http.HttpRequestHeadersHook(flow2)\n reqhook1 = http.HttpRequestHook(flow1)\n reqhook2 = http.HttpRequestHook(flow2)",
" server = Placeholder(Server)\n data_req1 = Placeholder(bytes)\n data_req2 = Placeholder(bytes)",
" assert (playbook\n >> DataReceived(\n tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=1).serialize() +\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=3).serialize())\n << reqheadershook1\n << reqheadershook2\n >> reply(to=reqheadershook1)\n << reqhook1\n >> reply(to=reqheadershook2)\n << reqhook2\n # req 2 overtakes 1 and we already have a reply:\n >> reply(to=reqhook2)\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, data_req2)\n >> reply(to=reqhook1)\n << SendData(server, data_req1)\n )\n frames = decode_frames(data_req2())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]\n frames = decode_frames(data_req1())\n assert [type(x) for x in frames] == [\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_max_concurrency(tctx):\n playbook, cff = start_h2_client(tctx)\n server = Placeholder(Server)\n req1_bytes = Placeholder(bytes)\n settings_ack_bytes = Placeholder(bytes)\n req2_bytes = Placeholder(bytes)\n playbook.hooks = False\n sff = FrameFactory()",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"],\n stream_id=1).serialize())\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, req1_bytes)\n >> DataReceived(server,\n sff.build_settings_frame(\n {h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 1}).serialize())\n << SendData(server, settings_ack_bytes)\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers,\n flags=[\"END_STREAM\"],\n stream_id=3).serialize())\n # Can't send it upstream yet, all streams in use!\n >> DataReceived(server, sff.build_headers_frame(example_response_headers,\n flags=[\"END_STREAM\"],\n stream_id=1).serialize())\n # But now we can!\n << SendData(server, req2_bytes)\n << SendData(tctx.client, Placeholder(bytes))\n >> DataReceived(server, sff.build_headers_frame(example_response_headers,\n flags=[\"END_STREAM\"],\n stream_id=3).serialize())\n << SendData(tctx.client, Placeholder(bytes))\n )\n settings, req1 = decode_frames(req1_bytes())\n settings_ack, = decode_frames(settings_ack_bytes())\n req2, = decode_frames(req2_bytes())",
" assert type(settings) == hyperframe.frame.SettingsFrame\n assert type(req1) == hyperframe.frame.HeadersFrame\n assert type(settings_ack) == hyperframe.frame.SettingsFrame\n assert type(req2) == hyperframe.frame.HeadersFrame\n assert req1.stream_id == 1\n assert req2.stream_id == 3",
"\ndef test_stream_concurrent_get_connection(tctx):\n \"\"\"Test that an immediate second request for the same domain does not trigger a second connection attempt.\"\"\"\n playbook, cff = start_h2_client(tctx)\n playbook.hooks = False",
" server = Placeholder(Server)\n data = Placeholder(bytes)",
" assert (playbook\n >> DataReceived(tctx.client, cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"],\n stream_id=1).serialize())\n << (o := OpenConnection(server))\n >> DataReceived(tctx.client, cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"],\n stream_id=3).serialize())\n >> reply(None, to=o, side_effect=make_h2)\n << SendData(server, data)\n )\n frames = decode_frames(data())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_kill_stream(tctx):\n \"\"\"Test that we can kill individual streams.\"\"\"\n playbook, cff = start_h2_client(tctx)\n flow1 = Placeholder(HTTPFlow)\n flow2 = Placeholder(HTTPFlow)",
" req_headers_hook_1 = http.HttpRequestHeadersHook(flow1)",
" def kill(flow: HTTPFlow):\n # Can't use flow.kill() here because that currently still depends on a reply object.\n flow.error = Error(Error.KILLED_MESSAGE)",
" server = Placeholder(Server)\n data_req1 = Placeholder(bytes)",
" assert (playbook\n >> DataReceived(\n tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=1).serialize() +\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"], stream_id=3).serialize())\n << req_headers_hook_1\n << http.HttpRequestHeadersHook(flow2)\n >> reply(side_effect=kill)\n << http.HttpErrorHook(flow2)\n >> reply()\n << SendData(tctx.client, cff.build_rst_stream_frame(3, error_code=ErrorCodes.INTERNAL_ERROR).serialize())\n >> reply(to=req_headers_hook_1)\n << http.HttpRequestHook(flow1)\n >> reply()\n << OpenConnection(server)\n >> reply(None, side_effect=make_h2)\n << SendData(server, data_req1)\n )\n frames = decode_frames(data_req1())\n assert [type(x) for x in frames] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.HeadersFrame,\n ]",
"\nclass TestClient:\n def test_no_data_on_closed_stream(self, tctx):\n frame_factory = FrameFactory()\n req = Request.make(\"GET\", \"http://example.com/\")\n resp = {\n \":status\": 200\n }\n assert (\n Playbook(Http2Client(tctx))\n << SendData(tctx.server, Placeholder(bytes)) # preamble + initial settings frame\n >> DataReceived(tctx.server, frame_factory.build_settings_frame({}, ack=True).serialize())\n >> http.RequestHeaders(1, req, end_stream=True)\n << SendData(tctx.server, b\"\\x00\\x00\\x06\\x01\\x05\\x00\\x00\\x00\\x01\\x82\\x86\\x84\\\\\\x81\\x07\")\n >> http.RequestEndOfMessage(1)\n >> DataReceived(tctx.server, frame_factory.build_headers_frame(resp).serialize())\n << http.ReceiveHttp(Placeholder(http.ResponseHeaders))\n >> http.RequestProtocolError(1, \"cancelled\", code=status_codes.CLIENT_CLOSED_REQUEST)\n << SendData(tctx.server, frame_factory.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())\n >> DataReceived(tctx.server, frame_factory.build_data_frame(b\"foo\").serialize())\n << SendData(tctx.server, frame_factory.build_rst_stream_frame(1, ErrorCodes.STREAM_CLOSED).serialize())\n ) # important: no ResponseData event here!",
"\ndef test_early_server_data(tctx):\n playbook, cff = start_h2_client(tctx)\n sff = FrameFactory()",
" tctx.server.address = (\"example.com\", 80)\n tctx.server.state = ConnectionState.OPEN\n tctx.server.alpn = b\"h2\"",
" flow = Placeholder(HTTPFlow)\n server1 = Placeholder(bytes)\n server2 = Placeholder(bytes)\n assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(example_request_headers, flags=[\"END_STREAM\"]).serialize())\n << http.HttpRequestHeadersHook(flow)\n >> reply()\n << (h := http.HttpRequestHook(flow))\n # Surprise! We get data from the server before the request hook finishes.\n >> DataReceived(tctx.server, sff.build_settings_frame({}).serialize())\n << SendData(tctx.server, server1)\n # Request hook finishes...\n >> reply(to=h)\n << SendData(tctx.server, server2)\n )\n assert [type(x) for x in decode_frames(server1())] == [\n hyperframe.frame.SettingsFrame,\n hyperframe.frame.SettingsFrame,\n ]\n assert [type(x) for x in decode_frames(server2())] == [\n hyperframe.frame.HeadersFrame,\n ]",
"\ndef test_request_smuggling_cl(tctx):\n playbook, cff = start_h2_client(tctx)\n playbook.hooks = False\n err = Placeholder(bytes)",
" headers = (\n (b':method', b'POST'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n (b'content-length', b'3')\n )",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(headers).serialize())\n >> DataReceived(tctx.client,\n cff.build_data_frame(b\"abcPOST / HTTP/1.1 ...\", flags=[\"END_STREAM\"]).serialize())\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"InvalidBodyLengthError\" in err()",
"\ndef test_request_smuggling_te(tctx):\n playbook, cff = start_h2_client(tctx)\n playbook.hooks = False\n err = Placeholder(bytes)",
" headers = (\n (b':method', b'POST'),\n (b':scheme', b'http'),\n (b':path', b'/'),\n (b':authority', b'example.com'),\n (b'transfer-encoding', b'chunked')\n )",
" assert (\n playbook\n >> DataReceived(tctx.client,\n cff.build_headers_frame(headers, flags=[\"END_STREAM\"]).serialize())\n << SendData(tctx.client, err)\n << CloseConnection(tctx.client)\n )\n assert b\"Connection-specific header field present\" in err()"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [98, 18, 108, 332, 60, 99, 1263, 359], "buggy_code_start_loc": [98, 5, 38, 236, 43, 7, 1263, 355], "filenames": ["mitmproxy/addons/proxyserver.py", "mitmproxy/net/http/http1/__init__.py", "mitmproxy/net/http/http1/read.py", "mitmproxy/proxy/layers/http/_http1.py", "mitmproxy/proxy/layers/http/_http2.py", "test/mitmproxy/net/http/http1/test_read.py", "test/mitmproxy/proxy/layers/http/test_http.py", "test/mitmproxy/proxy/layers/http/test_http2.py"], "fixing_code_end_loc": [106, 21, 138, 337, 62, 106, 1295, 360], "fixing_code_start_loc": [99, 6, 39, 237, 43, 7, 1264, 354], "message": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mitmproxy:mitmproxy:*:*:*:*:*:*:*:*", "matchCriteriaId": "41ABE70A-F0A7-4F97-A8F1-8B8D1BDD5663", "versionEndExcluding": null, "versionEndIncluding": "7.0.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "mitmproxy is an interactive, SSL/TLS-capable intercepting proxy. In mitmproxy 7.0.4 and below, a malicious client or server is able to perform HTTP request smuggling attacks through mitmproxy. This means that a malicious client/server could smuggle a request/response through mitmproxy as part of another request/response's HTTP message body. While mitmproxy would only see one request, the target server would see multiple requests. A smuggled request is still captured as part of another request's body, but it does not appear in the request list and does not go through the usual mitmproxy event hooks, where users may have implemented custom access control checks or input sanitization. Unless mitmproxy is used to protect an HTTP/1 service, no action is required. The vulnerability has been fixed in mitmproxy 8.0.0 and above. There are currently no known workarounds."}, {"lang": "es", "value": "mitmproxy es un proxy interactivo con capacidad de interceptaci\u00f3n SSL/TLS. En mitmproxy versiones 7.0.4 y anteriores, un cliente o servidor malicioso puede llevar a cabo ataques de contrabando de peticiones HTTP mediante mitmproxy. Esto significa que un cliente/servidor malicioso podr\u00eda pasar de contrabando una petici\u00f3n/respuesta mediante mitmproxy como parte del cuerpo del mensaje HTTP de otra petici\u00f3n/respuesta. Mientras que mitmproxy s\u00f3lo ver\u00eda una petici\u00f3n, el servidor de destino ver\u00eda m\u00faltiples peticiones. Una petici\u00f3n contrabandeada sigue siendo capturada como parte del cuerpo de otra petici\u00f3n, pero no aparece en la lista de peticiones y no pasa por los ganchos de eventos habituales de mitmproxy, donde los usuarios pueden haber implementado comprobaciones de control de acceso personalizadas o saneo de entradas. A menos que mitmproxy sea usado para proteger un servicio HTTP/1, no es requerida ninguna acci\u00f3n. La vulnerabilidad ha sido corregida en mitmproxy versiones 8.0.0 y superiores. Actualmente no se presentan medidas de mitigaci\u00f3n conocidas"}], "evaluatorComment": null, "id": "CVE-2022-24766", "lastModified": "2022-03-29T16:49:43.347", "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-03-21T19:15:11.613", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/mitmproxy/mitmproxy/security/advisories/GHSA-gcx2-gvj7-pxv3"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://mitmproxy.org/posts/releases/mitmproxy8/"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/mitmproxy/mitmproxy/commit/b06fb6d157087d526bd02e7aadbe37c56865c71b"}, "type": "CWE-444"}
| 306
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% M M AAA TTTTT L AAA BBBB %\n% MM MM A A T L A A B B %\n% M M M AAAAA T L AAAAA BBBB %\n% M M A A T L A A B B %\n% M M A A T LLLLL A A BBBB %\n% %\n% %\n% Read MATLAB Image Format %\n% %\n% Software Design %\n% Jaroslav Fojtik %\n% 2001-2008 %\n% %\n% %\n% Permission is hereby granted, free of charge, to any person obtaining a %\n% copy of this software and associated documentation files (\"ImageMagick\"), %\n% to deal in ImageMagick without restriction, including without limitation %\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, %\n% and/or sell copies of ImageMagick, and to permit persons to whom the %\n% ImageMagick is 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 ImageMagick. %\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 %\n% ImageMagick Studio be liable for any claim, damages or other liability, %\n% whether in an action of contract, tort or otherwise, arising from, out of %\n% or in connection with ImageMagick or the use or other dealings in %\n% ImageMagick. %\n% %\n% Except as contained in this notice, the name of the ImageMagick Studio %\n% shall not be used in advertising or otherwise to promote the sale, use or %\n% other dealings in ImageMagick without prior written authorization from the %\n% ImageMagick Studio. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/color-private.h\"\n#include \"MagickCore/colormap.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/distort.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/monitor.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/quantum.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel.h\"\n#include \"MagickCore/resource_.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/transform.h\"\n#include \"MagickCore/utility-private.h\"\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n #include \"zlib.h\"\n#endif\n\f\n/*\n Forward declaration.\n*/\nstatic MagickBooleanType\n WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);",
"\n/* Auto coloring method, sorry this creates some artefact inside data\nMinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black\nMinReal+j*0 = white MaxReal+j*0 = black\nMinReal+j*MinComplex = blue MaxReal+j*MinComplex = black\n*/",
"typedef struct\n{\n char identific[124];\n unsigned short Version;\n char EndianIndicator[2];\n unsigned long DataType;\n unsigned int ObjectSize;\n unsigned long unknown1;\n unsigned long unknown2;",
" unsigned short unknown5;\n unsigned char StructureFlag;\n unsigned char StructureClass;\n unsigned long unknown3;\n unsigned long unknown4;\n unsigned long DimFlag;",
" unsigned long SizeX;\n unsigned long SizeY;\n unsigned short Flag1;\n unsigned short NameFlag;\n}\nMATHeader;",
"static const char *MonthsTab[12]={\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\nstatic const char *DayOfWTab[7]={\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"};\nstatic const char *OsDesc=\n#if defined(MAGICKCORE_WINDOWS_SUPPORT)\n \"PCWIN\";\n#else\n #ifdef __APPLE__\n \"MAC\";\n #else\n \"LNX86\";\n #endif\n#endif",
"typedef enum\n {\n miINT8 = 1, /* 8 bit signed */\n miUINT8, /* 8 bit unsigned */\n miINT16, /* 16 bit signed */\n miUINT16, /* 16 bit unsigned */\n miINT32, /* 32 bit signed */\n miUINT32, /* 32 bit unsigned */\n miSINGLE, /* IEEE 754 single precision float */\n miRESERVE1,\n miDOUBLE, /* IEEE 754 double precision float */\n miRESERVE2,\n miRESERVE3,\n miINT64, /* 64 bit signed */\n miUINT64, /* 64 bit unsigned */\n miMATRIX, /* MATLAB array */\n miCOMPRESSED, /* Compressed Data */\n miUTF8, /* Unicode UTF-8 Encoded Character Data */\n miUTF16, /* Unicode UTF-16 Encoded Character Data */\n miUTF32 /* Unicode UTF-32 Encoded Character Data */\n } mat5_data_type;",
"typedef enum\n {\n mxCELL_CLASS=1, /* cell array */\n mxSTRUCT_CLASS, /* structure */\n mxOBJECT_CLASS, /* object */\n mxCHAR_CLASS, /* character array */\n mxSPARSE_CLASS, /* sparse array */\n mxDOUBLE_CLASS, /* double precision array */\n mxSINGLE_CLASS, /* single precision floating point */\n mxINT8_CLASS, /* 8 bit signed integer */\n mxUINT8_CLASS, /* 8 bit unsigned integer */\n mxINT16_CLASS, /* 16 bit signed integer */\n mxUINT16_CLASS, /* 16 bit unsigned integer */\n mxINT32_CLASS, /* 32 bit signed integer */\n mxUINT32_CLASS, /* 32 bit unsigned integer */\n mxINT64_CLASS, /* 64 bit signed integer */\n mxUINT64_CLASS, /* 64 bit unsigned integer */\n mxFUNCTION_CLASS /* Function handle */\n } arrayclasstype;",
"#define FLAG_COMPLEX 0x8\n#define FLAG_GLOBAL 0x4\n#define FLAG_LOGICAL 0x2",
"static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};",
"\nstatic void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal,\n double MaxVal,ExceptionInfo *exception)\n{",
" double f;\n int x;\n register Quantum *q;",
" if (MinVal == 0)\n MinVal = -1;\n if (MaxVal == 0)\n MaxVal = 1;",
" q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return;\n for (x = 0; x < (ssize_t) image->columns; x++)\n {\n if (*p > 0)\n {\n f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));\n if (f + GetPixelRed(image,q) > QuantumRange)\n SetPixelRed(image,QuantumRange,q);\n else\n SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n }\n else\n {\n SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelBlue(image,q),q);\n }\n }\n if (*p < 0)\n {\n f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q));\n if (f+GetPixelBlue(image,q) > QuantumRange)\n SetPixelBlue(image,QuantumRange,q);\n else\n SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelRed(image,0,q);\n SetPixelGreen(image,0,q);\n }\n else\n {\n SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelRed(image,q),q);\n }\n }\n p++;\n q+=GetPixelChannels(image);\n }\n if (!SyncAuthenticPixels(image,exception))\n return;\n return;\n}",
"\nstatic void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,\n double MaxVal,ExceptionInfo *exception)\n{\n double f;\n int x;\n register Quantum *q;",
" if (MinVal == 0)\n MinVal = -1;\n if (MaxVal == 0)\n MaxVal = 1;",
" q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);\n if (q == (Quantum *) NULL)\n return;\n for (x = 0; x < (ssize_t) image->columns; x++)\n {\n if (*p > 0)\n {\n f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));\n if (f+GetPixelRed(image,q) > QuantumRange)\n SetPixelRed(image,QuantumRange,q);\n else\n SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n }\n else\n {\n SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelBlue(image,q),q);\n }\n }\n if (*p < 0)\n {\n f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));\n if (f + GetPixelBlue(image,q) > QuantumRange)\n SetPixelBlue(image,QuantumRange,q);\n else\n SetPixelBlue(image,GetPixelBlue(image,q)+\n (int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelGreen(image,0,q);\n SetPixelRed(image,0,q);\n }\n else\n {\n SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelRed(image,q),q);\n }\n }\n p++;\n q++;\n }\n if (!SyncAuthenticPixels(image,exception))\n return;\n return;\n}",
"\n/************** READERS ******************/",
"/* This function reads one block of floats*/\nstatic void ReadBlobFloatsLSB(Image * image, size_t len, float *data)\n{\n while (len >= 4)\n {\n *data++ = ReadBlobFloat(image);\n len -= sizeof(float);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)\n{\n while (len >= 4)\n {\n *data++ = ReadBlobFloat(image);\n len -= sizeof(float);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"/* This function reads one block of doubles*/\nstatic void ReadBlobDoublesLSB(Image * image, size_t len, double *data)\n{\n while (len >= 8)\n {\n *data++ = ReadBlobDouble(image);\n len -= sizeof(double);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)\n{\n while (len >= 8)\n {\n *data++ = ReadBlobDouble(image);\n len -= sizeof(double);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"/* Calculate minimum and maximum from a given block of data */\nstatic void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)\n{\nMagickOffsetType filepos;\nint i, x;\nvoid (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\nvoid (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\ndouble *dblrow;\nfloat *fltrow;",
" if (endian_indicator == LSBEndian)\n {\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n }\n else /* MI */\n {\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n }",
" filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */\n for (i = 0; i < SizeY; i++)\n {\n if (CellType==miDOUBLE)\n {\n ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);\n dblrow = (double *)BImgBuff;\n if (i == 0)\n {\n *Min = *Max = *dblrow;\n }\n for (x = 0; x < SizeX; x++)\n {\n if (*Min > *dblrow)\n *Min = *dblrow;\n if (*Max < *dblrow)\n *Max = *dblrow;\n dblrow++;\n }\n }\n if (CellType==miSINGLE)\n {\n ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);\n fltrow = (float *)BImgBuff;\n if (i == 0)\n {\n *Min = *Max = *fltrow;\n }\n for (x = 0; x < (ssize_t) SizeX; x++)\n {\n if (*Min > *fltrow)\n *Min = *fltrow;\n if (*Max < *fltrow)\n *Max = *fltrow;\n fltrow++;\n }\n }\n }\n (void) SeekBlob(image, filepos, SEEK_SET);\n}",
"\nstatic void FixSignedValues(const Image *image,Quantum *q, int y)\n{\n while(y-->0)\n {\n /* Please note that negative values will overflow\n Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>\n <-1;-128> + 127+1 = <0; 127> */\n SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);\n SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);\n SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);\n q++;\n }\n}",
"\n/** Fix whole row of logical/binary data. It means pack it. */\nstatic void FixLogical(unsigned char *Buff,int ldblk)\n{\nunsigned char mask=128;\nunsigned char *BuffL = Buff;\nunsigned char val = 0;",
" while(ldblk-->0)\n {\n if(*Buff++ != 0)\n val |= mask;",
" mask >>= 1;\n if(mask==0)\n {\n *BuffL++ = val;\n val = 0;\n mask = 128;\n }",
" }\n *BuffL = val;\n}",
"#if defined(MAGICKCORE_ZLIB_DELEGATE)\nstatic voidpf AcquireZIPMemory(voidpf context,unsigned int items,\n unsigned int size)\n{\n (void) context;\n return((voidpf) AcquireQuantumMemory(items,size));\n}",
"static void RelinquishZIPMemory(voidpf context,voidpf memory)\n{\n (void) context;\n memory=RelinquishMagickMemory(memory);\n}\n#endif",
"#if defined(MAGICKCORE_ZLIB_DELEGATE)\n/** This procedure decompreses an image block for a new MATLAB format. */\nstatic Image *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception)\n{",
"Image *image2;\nvoid *cache_block, *decompress_block;\nz_stream zip_info;\nFILE *mat_file;\nsize_t magick_size;\nsize_t extent;\nint file;",
"int status;\nint zip_status;\nssize_t TotalSize = 0;",
" if(clone_info==NULL) return NULL;\n if(clone_info->file) /* Close file opened from previous transaction. */\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }",
" cache_block = AcquireQuantumMemory((size_t)(*Size < 16384) ? *Size: 16384,sizeof(unsigned char *));\n if(cache_block==NULL) return NULL;\n decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));\n if(decompress_block==NULL)\n {\n RelinquishMagickMemory(cache_block);\n return NULL;\n }",
" mat_file=0;\n file = AcquireUniqueFileResource(clone_info->filename);\n if (file != -1)\n mat_file = fdopen(file,\"w\");\n if(!mat_file)\n {\n RelinquishMagickMemory(cache_block);\n RelinquishMagickMemory(decompress_block);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Cannot create file stream for decompressed image\");\n return NULL;\n }",
" zip_info.zalloc=AcquireZIPMemory;\n zip_info.zfree=RelinquishZIPMemory;\n zip_info.opaque = (voidpf) NULL;\n zip_status = inflateInit(&zip_info);\n if (zip_status != Z_OK)\n {\n RelinquishMagickMemory(cache_block);\n RelinquishMagickMemory(decompress_block);\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"UnableToUncompressImage\",\"`%s'\",clone_info->filename);\n (void) fclose(mat_file);\n RelinquishUniqueFileResource(clone_info->filename);\n return NULL;\n }\n /* zip_info.next_out = 8*4;*/",
" zip_info.avail_in = 0;\n zip_info.total_out = 0;\n while(*Size>0 && !EOFBlob(orig))\n {\n magick_size = ReadBlob(orig, (*Size < 16384) ? *Size : 16384, (unsigned char *) cache_block);\n zip_info.next_in = (Bytef *) cache_block;\n zip_info.avail_in = (uInt) magick_size;",
" while(zip_info.avail_in>0)\n {\n zip_info.avail_out = 4096;\n zip_info.next_out = (Bytef *) decompress_block;\n zip_status = inflate(&zip_info,Z_NO_FLUSH);\n if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))\n break;\n extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file);\n (void) extent;\n TotalSize += 4096-zip_info.avail_out;",
" if(zip_status == Z_STREAM_END) goto DblBreak;\n }\n if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))\n break;",
" *Size -= magick_size;\n }\nDblBreak:",
" inflateEnd(&zip_info);\n (void)fclose(mat_file);\n RelinquishMagickMemory(cache_block);\n RelinquishMagickMemory(decompress_block);\n *Size = TotalSize;",
" if((clone_info->file=fopen(clone_info->filename,\"rb\"))==NULL) goto UnlinkFile;\n if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;\n status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n DeleteImageFromList(&image2);\nEraseFile:\n fclose(clone_info->file);\n clone_info->file = NULL;\nUnlinkFile:\n RelinquishUniqueFileResource(clone_info->filename);\n return NULL;\n }",
" return image2;\n}\n#endif",
"static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n typedef struct {\n unsigned char Type[4];\n unsigned int nRows;\n unsigned int nCols;\n unsigned int imagf;\n unsigned int nameLen;\n } MAT4_HDR;",
" long\n ldblk;",
" EndianType\n endian;",
" Image\n *rotate_image;",
" MagickBooleanType\n status;",
" MAT4_HDR\n HDR;",
" QuantumInfo\n *quantum_info;",
" QuantumFormatType\n format_type;",
" register ssize_t\n i;",
" ssize_t\n count,\n y;",
" unsigned char\n *pixels;",
" unsigned int\n depth;",
"\n quantum_info=(QuantumInfo *) NULL;\n (void) SeekBlob(image,0,SEEK_SET);\n while (EOFBlob(image) != MagickFalse)\n {\n /*\n Object parser loop.\n */\n ldblk=ReadBlobLSBLong(image);\n if ((ldblk > 9999) || (ldblk < 0))\n break;\n HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */\n HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */\n HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */\n HDR.Type[0]=ldblk; /* M digit */\n if (HDR.Type[3] != 0)\n break; /* Data format */\n if (HDR.Type[2] != 0)\n break; /* Always 0 */\n if (HDR.Type[0] == 0)\n {\n HDR.nRows=ReadBlobLSBLong(image);\n HDR.nCols=ReadBlobLSBLong(image);\n HDR.imagf=ReadBlobLSBLong(image);\n HDR.nameLen=ReadBlobLSBLong(image);\n endian=LSBEndian;\n }\n else\n {\n HDR.nRows=ReadBlobMSBLong(image);\n HDR.nCols=ReadBlobMSBLong(image);\n HDR.imagf=ReadBlobMSBLong(image);\n HDR.nameLen=ReadBlobMSBLong(image);\n endian=MSBEndian;\n }\n if ((HDR.imagf != 0) && (HDR.imagf != 1))\n break;\n if (HDR.nameLen > 0xFFFF)\n return((Image *) NULL);\n for (i=0; i < (ssize_t) HDR.nameLen; i++)\n {\n int\n byte;",
" /*\n Skip matrix name.\n */\n byte=ReadBlobByte(image);\n if (byte == EOF)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n }\n image->columns=(size_t) HDR.nRows;\n image->rows=(size_t) HDR.nCols;\n SetImageColorspace(image,GRAYColorspace,exception);\n if (image_info->ping != MagickFalse)\n {\n Swap(image->columns,image->rows);\n return(image);\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return((Image *) NULL);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n return((Image *) NULL);\n switch(HDR.Type[1])\n {\n case 0:\n format_type=FloatingPointQuantumFormat;\n depth=64;\n break;\n case 1:\n format_type=FloatingPointQuantumFormat;\n depth=32;\n break;\n case 2:\n format_type=UnsignedQuantumFormat;\n depth=16;\n break;\n case 3:\n format_type=SignedQuantumFormat;\n depth=16;\n break;\n case 4:\n format_type=UnsignedQuantumFormat;\n depth=8;\n break;\n default:\n format_type=UnsignedQuantumFormat;\n depth=8;\n break;\n }\n image->depth=depth;\n if (HDR.Type[0] != 0)\n SetQuantumEndian(image,quantum_info,MSBEndian);\n status=SetQuantumFormat(image,quantum_info,format_type);\n status=SetQuantumDepth(image,quantum_info,depth);\n status=SetQuantumEndian(image,quantum_info,endian);\n SetQuantumScale(quantum_info,1.0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n if (count == -1)\n break;\n q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,pixels,exception);\n if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))\n FixSignedValues(image,q,(int) image->columns);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (HDR.imagf == 1)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n /*\n Read complex pixels.\n */\n count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n if (count == -1)\n break;\n if (HDR.Type[1] == 0)\n InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);\n else\n InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);\n }\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n rotate_image=RotateImage(image,90.0,exception);\n if (rotate_image != (Image *) NULL)\n {\n image=DestroyImage(image);\n image=rotate_image;\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d M A T L A B i m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadMATImage() reads an MAT X image file and returns it. It\n% allocates the memory necessary for the new Image structure and returns a\n% pointer to the new image.\n%\n% The format of the ReadMATImage method is:\n%\n% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: Method ReadMATImage returns a pointer to the image after\n% reading. A null image is returned if there is a memory shortage or if\n% the image cannot be read.\n%\n% o image_info: Specifies a pointer to a ImageInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;",
" unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;",
" unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);",
"\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");",
" /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);",
" status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");",
" if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */",
" if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n if (clone_info != (ImageInfo *) NULL)\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }",
" filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */",
" MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;",
" clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif",
" if (MATLAB_HDR.DataType!=miMATRIX)\n {\n clone_info=DestroyImageInfo(clone_info);\n continue; /* skip another objects. */\n }",
" MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);",
" MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;",
" MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);",
"\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default:\n if (clone_info != (ImageInfo *) NULL)\n clone_info=DestroyImageInfo(clone_info);\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }",
" MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);",
" if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");",
" switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }",
" CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);",
" (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */",
" NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }",
"\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n return(DestroyImageList(image));\n }\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");",
" /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));",
" MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }",
" /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;",
"\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }",
" if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:",
"\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/",
" if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }",
" if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }",
" if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }",
" /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;",
" if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */",
" /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;",
" blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }",
"done_reading:",
" if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }",
" /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;",
" /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;",
" if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }",
" if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n }",
" RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:",
" if (clone_info)\n clone_info=DestroyImageInfo(clone_info);",
" CloseBlob(image);",
"\n {\n Image *p;\n ssize_t scene=0;",
" /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;",
"",
" DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }",
" /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }",
" if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if (image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\")\n else\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n return (image);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r M A T I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Method RegisterMATImage adds attributes for the MAT image format to\n% the list of supported formats. The attributes include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterMATImage method is:\n%\n% size_t RegisterMATImage(void)\n%\n*/\nModuleExport size_t RegisterMATImage(void)\n{\n MagickInfo\n *entry;",
" entry=AcquireMagickInfo(\"MAT\",\"MAT\",\"MATLAB level 5 image format\");\n entry->decoder=(DecodeImageHandler *) ReadMATImage;\n entry->encoder=(EncodeImageHandler *) WriteMATImage;\n entry->flags^=CoderBlobSupportFlag;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r M A T I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Method UnregisterMATImage removes format registrations made by the\n% MAT module from the list of supported formats.\n%\n% The format of the UnregisterMATImage method is:\n%\n% UnregisterMATImage(void)\n%\n*/\nModuleExport void UnregisterMATImage(void)\n{\n (void) UnregisterMagickInfo(\"MAT\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e M A T L A B I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function WriteMATImage writes an Matlab matrix to a file.\n%\n% The format of the WriteMATImage method is:\n%\n% MagickBooleanType WriteMATImage(const ImageInfo *image_info,\n% Image *image,ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: Specifies a pointer to a ImageInfo structure.\n%\n% o image: A pointer to an Image structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n MATLAB_HDR[0x80];",
" MagickBooleanType\n status;",
" MagickOffsetType\n scene;",
" struct tm\n local_time;",
" time_t\n current_time;",
" /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"enter MAT\");\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(MagickFalse);\n image->depth=8;",
" current_time=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(¤t_time,&local_time);\n#else\n (void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));\n#endif\n (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));\n FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),\n \"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d\",\n OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],\n local_time.tm_mday,local_time.tm_hour,local_time.tm_min,\n local_time.tm_sec,local_time.tm_year+1900);\n MATLAB_HDR[0x7C]=0;\n MATLAB_HDR[0x7D]=1;\n MATLAB_HDR[0x7E]='I';\n MATLAB_HDR[0x7F]='M';\n (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);\n scene=0;\n do\n {\n char\n padding;",
" MagickBooleanType\n is_gray;",
" QuantumInfo\n *quantum_info;",
" size_t\n data_size;",
" unsigned char\n *pixels;",
" unsigned int\n z;",
" (void) TransformImageColorspace(image,sRGBColorspace,exception);\n is_gray=SetImageGray(image,exception);\n z=(is_gray != MagickFalse) ? 0 : 3;",
" /*\n Store MAT header.\n */\n data_size = image->rows * image->columns;\n if (is_gray == MagickFalse)\n data_size*=3;\n padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7;",
" (void) WriteBlobLSBLong(image,miMATRIX);\n (void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+\n ((is_gray != MagickFalse) ? 48 : 56));\n (void) WriteBlobLSBLong(image,0x6); /* 0x88 */\n (void) WriteBlobLSBLong(image,0x8); /* 0x8C */\n (void) WriteBlobLSBLong(image,0x6); /* 0x90 */\n (void) WriteBlobLSBLong(image,0);\n (void) WriteBlobLSBLong(image,0x5); /* 0x98 */\n (void) WriteBlobLSBLong(image,(is_gray != MagickFalse) ? 0x8 : 0xC); /* 0x9C - DimFlag */\n (void) WriteBlobLSBLong(image,(unsigned int) image->rows); /* x: 0xA0 */\n (void) WriteBlobLSBLong(image,(unsigned int) image->columns); /* y: 0xA4 */\n if (is_gray == MagickFalse)\n {\n (void) WriteBlobLSBLong(image,3); /* z: 0xA8 */\n (void) WriteBlobLSBLong(image,0);\n }\n (void) WriteBlobLSBShort(image,1); /* 0xB0 */\n (void) WriteBlobLSBShort(image,1); /* 0xB2 */\n (void) WriteBlobLSBLong(image,'M'); /* 0xB4 */\n (void) WriteBlobLSBLong(image,0x2); /* 0xB8 */\n (void) WriteBlobLSBLong(image,(unsigned int) data_size); /* 0xBC */",
" /*\n Store image data.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n do\n {\n const Quantum\n *p;",
" ssize_t\n y;",
" for (y=0; y < (ssize_t)image->columns; y++)\n {\n p=GetVirtualPixels(image,y,0,1,image->rows,exception);\n if (p == (const Quantum *) NULL)\n break;\n (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n z2qtype[z],pixels,exception);\n (void) WriteBlob(image,image->rows,pixels);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n } while (z-- >= 2);\n while (padding-- > 0)\n (void) WriteBlobByte(image,0);\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(status);\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,
0,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1354], "buggy_code_start_loc": [1336], "filenames": ["coders/mat.c"], "fixing_code_end_loc": [1355], "fixing_code_start_loc": [1335], "message": "Use-after-free vulnerability in the DestroyImage function in image.c in ImageMagick before 7.0.6-6 allows remote attackers to cause a denial of service via a crafted file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "1CC65CC8-1DD1-4576-ABD7-939E3A8DEF50", "versionEndExcluding": "6.9.9-6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E545DED-03D1-40A4-83C6-35FE50868C26", "versionEndExcluding": "7.0.6-6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.0-0", "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}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "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:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use-after-free vulnerability in the DestroyImage function in image.c in ImageMagick before 7.0.6-6 allows remote attackers to cause a denial of service via a crafted file."}, {"lang": "es", "value": "Una vulnerabilidad de uso de memoria antes de liberaci\u00f3n (use-after-free)en la funci\u00f3n DestroyImage en image.c de ImageMagick para versiones anteriores a la 7.0.6-6 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio mediante un archivo manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12877", "lastModified": "2021-04-28T18:12:36.983", "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": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-08-28T19:29:00.790", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/08/16/2"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory", "VDB Entry"], "url": "https://blogs.gentoo.org/ago/2017/08/10/imagemagick-use-after-free-in-destroyimage-image-c/"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/04178de2247e353fc095846784b9a10fefdbf890"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201711-07"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3681-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2017/dsa-4040"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2017/dsa-4074"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/04178de2247e353fc095846784b9a10fefdbf890"}, "type": "CWE-416"}
| 307
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% M M AAA TTTTT L AAA BBBB %\n% MM MM A A T L A A B B %\n% M M M AAAAA T L AAAAA BBBB %\n% M M A A T L A A B B %\n% M M A A T LLLLL A A BBBB %\n% %\n% %\n% Read MATLAB Image Format %\n% %\n% Software Design %\n% Jaroslav Fojtik %\n% 2001-2008 %\n% %\n% %\n% Permission is hereby granted, free of charge, to any person obtaining a %\n% copy of this software and associated documentation files (\"ImageMagick\"), %\n% to deal in ImageMagick without restriction, including without limitation %\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, %\n% and/or sell copies of ImageMagick, and to permit persons to whom the %\n% ImageMagick is 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 ImageMagick. %\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 %\n% ImageMagick Studio be liable for any claim, damages or other liability, %\n% whether in an action of contract, tort or otherwise, arising from, out of %\n% or in connection with ImageMagick or the use or other dealings in %\n% ImageMagick. %\n% %\n% Except as contained in this notice, the name of the ImageMagick Studio %\n% shall not be used in advertising or otherwise to promote the sale, use or %\n% other dealings in ImageMagick without prior written authorization from the %\n% ImageMagick Studio. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/color-private.h\"\n#include \"MagickCore/colormap.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/distort.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/monitor.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/quantum.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel.h\"\n#include \"MagickCore/resource_.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/transform.h\"\n#include \"MagickCore/utility-private.h\"\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n #include \"zlib.h\"\n#endif\n\f\n/*\n Forward declaration.\n*/\nstatic MagickBooleanType\n WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);",
"\n/* Auto coloring method, sorry this creates some artefact inside data\nMinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black\nMinReal+j*0 = white MaxReal+j*0 = black\nMinReal+j*MinComplex = blue MaxReal+j*MinComplex = black\n*/",
"typedef struct\n{\n char identific[124];\n unsigned short Version;\n char EndianIndicator[2];\n unsigned long DataType;\n unsigned int ObjectSize;\n unsigned long unknown1;\n unsigned long unknown2;",
" unsigned short unknown5;\n unsigned char StructureFlag;\n unsigned char StructureClass;\n unsigned long unknown3;\n unsigned long unknown4;\n unsigned long DimFlag;",
" unsigned long SizeX;\n unsigned long SizeY;\n unsigned short Flag1;\n unsigned short NameFlag;\n}\nMATHeader;",
"static const char *MonthsTab[12]={\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\nstatic const char *DayOfWTab[7]={\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"};\nstatic const char *OsDesc=\n#if defined(MAGICKCORE_WINDOWS_SUPPORT)\n \"PCWIN\";\n#else\n #ifdef __APPLE__\n \"MAC\";\n #else\n \"LNX86\";\n #endif\n#endif",
"typedef enum\n {\n miINT8 = 1, /* 8 bit signed */\n miUINT8, /* 8 bit unsigned */\n miINT16, /* 16 bit signed */\n miUINT16, /* 16 bit unsigned */\n miINT32, /* 32 bit signed */\n miUINT32, /* 32 bit unsigned */\n miSINGLE, /* IEEE 754 single precision float */\n miRESERVE1,\n miDOUBLE, /* IEEE 754 double precision float */\n miRESERVE2,\n miRESERVE3,\n miINT64, /* 64 bit signed */\n miUINT64, /* 64 bit unsigned */\n miMATRIX, /* MATLAB array */\n miCOMPRESSED, /* Compressed Data */\n miUTF8, /* Unicode UTF-8 Encoded Character Data */\n miUTF16, /* Unicode UTF-16 Encoded Character Data */\n miUTF32 /* Unicode UTF-32 Encoded Character Data */\n } mat5_data_type;",
"typedef enum\n {\n mxCELL_CLASS=1, /* cell array */\n mxSTRUCT_CLASS, /* structure */\n mxOBJECT_CLASS, /* object */\n mxCHAR_CLASS, /* character array */\n mxSPARSE_CLASS, /* sparse array */\n mxDOUBLE_CLASS, /* double precision array */\n mxSINGLE_CLASS, /* single precision floating point */\n mxINT8_CLASS, /* 8 bit signed integer */\n mxUINT8_CLASS, /* 8 bit unsigned integer */\n mxINT16_CLASS, /* 16 bit signed integer */\n mxUINT16_CLASS, /* 16 bit unsigned integer */\n mxINT32_CLASS, /* 32 bit signed integer */\n mxUINT32_CLASS, /* 32 bit unsigned integer */\n mxINT64_CLASS, /* 64 bit signed integer */\n mxUINT64_CLASS, /* 64 bit unsigned integer */\n mxFUNCTION_CLASS /* Function handle */\n } arrayclasstype;",
"#define FLAG_COMPLEX 0x8\n#define FLAG_GLOBAL 0x4\n#define FLAG_LOGICAL 0x2",
"static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};",
"\nstatic void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal,\n double MaxVal,ExceptionInfo *exception)\n{",
" double f;\n int x;\n register Quantum *q;",
" if (MinVal == 0)\n MinVal = -1;\n if (MaxVal == 0)\n MaxVal = 1;",
" q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return;\n for (x = 0; x < (ssize_t) image->columns; x++)\n {\n if (*p > 0)\n {\n f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));\n if (f + GetPixelRed(image,q) > QuantumRange)\n SetPixelRed(image,QuantumRange,q);\n else\n SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n }\n else\n {\n SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelBlue(image,q),q);\n }\n }\n if (*p < 0)\n {\n f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q));\n if (f+GetPixelBlue(image,q) > QuantumRange)\n SetPixelBlue(image,QuantumRange,q);\n else\n SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelRed(image,0,q);\n SetPixelGreen(image,0,q);\n }\n else\n {\n SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelRed(image,q),q);\n }\n }\n p++;\n q+=GetPixelChannels(image);\n }\n if (!SyncAuthenticPixels(image,exception))\n return;\n return;\n}",
"\nstatic void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,\n double MaxVal,ExceptionInfo *exception)\n{\n double f;\n int x;\n register Quantum *q;",
" if (MinVal == 0)\n MinVal = -1;\n if (MaxVal == 0)\n MaxVal = 1;",
" q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);\n if (q == (Quantum *) NULL)\n return;\n for (x = 0; x < (ssize_t) image->columns; x++)\n {\n if (*p > 0)\n {\n f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q));\n if (f+GetPixelRed(image,q) > QuantumRange)\n SetPixelRed(image,QuantumRange,q);\n else\n SetPixelRed(image,GetPixelRed(image,q)+(int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelGreen(image,0,q);\n SetPixelBlue(image,0,q);\n }\n else\n {\n SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelBlue(image,q),q);\n }\n }\n if (*p < 0)\n {\n f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q));\n if (f + GetPixelBlue(image,q) > QuantumRange)\n SetPixelBlue(image,QuantumRange,q);\n else\n SetPixelBlue(image,GetPixelBlue(image,q)+\n (int) f,q);\n if ((int) f / 2.0 > GetPixelGreen(image,q))\n {\n SetPixelGreen(image,0,q);\n SetPixelRed(image,0,q);\n }\n else\n {\n SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q);\n SetPixelGreen(image,GetPixelRed(image,q),q);\n }\n }\n p++;\n q++;\n }\n if (!SyncAuthenticPixels(image,exception))\n return;\n return;\n}",
"\n/************** READERS ******************/",
"/* This function reads one block of floats*/\nstatic void ReadBlobFloatsLSB(Image * image, size_t len, float *data)\n{\n while (len >= 4)\n {\n *data++ = ReadBlobFloat(image);\n len -= sizeof(float);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)\n{\n while (len >= 4)\n {\n *data++ = ReadBlobFloat(image);\n len -= sizeof(float);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"/* This function reads one block of doubles*/\nstatic void ReadBlobDoublesLSB(Image * image, size_t len, double *data)\n{\n while (len >= 8)\n {\n *data++ = ReadBlobDouble(image);\n len -= sizeof(double);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)\n{\n while (len >= 8)\n {\n *data++ = ReadBlobDouble(image);\n len -= sizeof(double);\n }\n if (len > 0)\n (void) SeekBlob(image, len, SEEK_CUR);\n}",
"/* Calculate minimum and maximum from a given block of data */\nstatic void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)\n{\nMagickOffsetType filepos;\nint i, x;\nvoid (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\nvoid (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\ndouble *dblrow;\nfloat *fltrow;",
" if (endian_indicator == LSBEndian)\n {\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n }\n else /* MI */\n {\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n }",
" filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */\n for (i = 0; i < SizeY; i++)\n {\n if (CellType==miDOUBLE)\n {\n ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);\n dblrow = (double *)BImgBuff;\n if (i == 0)\n {\n *Min = *Max = *dblrow;\n }\n for (x = 0; x < SizeX; x++)\n {\n if (*Min > *dblrow)\n *Min = *dblrow;\n if (*Max < *dblrow)\n *Max = *dblrow;\n dblrow++;\n }\n }\n if (CellType==miSINGLE)\n {\n ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);\n fltrow = (float *)BImgBuff;\n if (i == 0)\n {\n *Min = *Max = *fltrow;\n }\n for (x = 0; x < (ssize_t) SizeX; x++)\n {\n if (*Min > *fltrow)\n *Min = *fltrow;\n if (*Max < *fltrow)\n *Max = *fltrow;\n fltrow++;\n }\n }\n }\n (void) SeekBlob(image, filepos, SEEK_SET);\n}",
"\nstatic void FixSignedValues(const Image *image,Quantum *q, int y)\n{\n while(y-->0)\n {\n /* Please note that negative values will overflow\n Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>\n <-1;-128> + 127+1 = <0; 127> */\n SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);\n SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);\n SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);\n q++;\n }\n}",
"\n/** Fix whole row of logical/binary data. It means pack it. */\nstatic void FixLogical(unsigned char *Buff,int ldblk)\n{\nunsigned char mask=128;\nunsigned char *BuffL = Buff;\nunsigned char val = 0;",
" while(ldblk-->0)\n {\n if(*Buff++ != 0)\n val |= mask;",
" mask >>= 1;\n if(mask==0)\n {\n *BuffL++ = val;\n val = 0;\n mask = 128;\n }",
" }\n *BuffL = val;\n}",
"#if defined(MAGICKCORE_ZLIB_DELEGATE)\nstatic voidpf AcquireZIPMemory(voidpf context,unsigned int items,\n unsigned int size)\n{\n (void) context;\n return((voidpf) AcquireQuantumMemory(items,size));\n}",
"static void RelinquishZIPMemory(voidpf context,voidpf memory)\n{\n (void) context;\n memory=RelinquishMagickMemory(memory);\n}\n#endif",
"#if defined(MAGICKCORE_ZLIB_DELEGATE)\n/** This procedure decompreses an image block for a new MATLAB format. */\nstatic Image *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception)\n{",
"Image *image2;\nvoid *cache_block, *decompress_block;\nz_stream zip_info;\nFILE *mat_file;\nsize_t magick_size;\nsize_t extent;\nint file;",
"int status;\nint zip_status;\nssize_t TotalSize = 0;",
" if(clone_info==NULL) return NULL;\n if(clone_info->file) /* Close file opened from previous transaction. */\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }",
" cache_block = AcquireQuantumMemory((size_t)(*Size < 16384) ? *Size: 16384,sizeof(unsigned char *));\n if(cache_block==NULL) return NULL;\n decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));\n if(decompress_block==NULL)\n {\n RelinquishMagickMemory(cache_block);\n return NULL;\n }",
" mat_file=0;\n file = AcquireUniqueFileResource(clone_info->filename);\n if (file != -1)\n mat_file = fdopen(file,\"w\");\n if(!mat_file)\n {\n RelinquishMagickMemory(cache_block);\n RelinquishMagickMemory(decompress_block);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"Cannot create file stream for decompressed image\");\n return NULL;\n }",
" zip_info.zalloc=AcquireZIPMemory;\n zip_info.zfree=RelinquishZIPMemory;\n zip_info.opaque = (voidpf) NULL;\n zip_status = inflateInit(&zip_info);\n if (zip_status != Z_OK)\n {\n RelinquishMagickMemory(cache_block);\n RelinquishMagickMemory(decompress_block);\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"UnableToUncompressImage\",\"`%s'\",clone_info->filename);\n (void) fclose(mat_file);\n RelinquishUniqueFileResource(clone_info->filename);\n return NULL;\n }\n /* zip_info.next_out = 8*4;*/",
" zip_info.avail_in = 0;\n zip_info.total_out = 0;\n while(*Size>0 && !EOFBlob(orig))\n {\n magick_size = ReadBlob(orig, (*Size < 16384) ? *Size : 16384, (unsigned char *) cache_block);\n zip_info.next_in = (Bytef *) cache_block;\n zip_info.avail_in = (uInt) magick_size;",
" while(zip_info.avail_in>0)\n {\n zip_info.avail_out = 4096;\n zip_info.next_out = (Bytef *) decompress_block;\n zip_status = inflate(&zip_info,Z_NO_FLUSH);\n if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))\n break;\n extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file);\n (void) extent;\n TotalSize += 4096-zip_info.avail_out;",
" if(zip_status == Z_STREAM_END) goto DblBreak;\n }\n if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))\n break;",
" *Size -= magick_size;\n }\nDblBreak:",
" inflateEnd(&zip_info);\n (void)fclose(mat_file);\n RelinquishMagickMemory(cache_block);\n RelinquishMagickMemory(decompress_block);\n *Size = TotalSize;",
" if((clone_info->file=fopen(clone_info->filename,\"rb\"))==NULL) goto UnlinkFile;\n if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;\n status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n DeleteImageFromList(&image2);\nEraseFile:\n fclose(clone_info->file);\n clone_info->file = NULL;\nUnlinkFile:\n RelinquishUniqueFileResource(clone_info->filename);\n return NULL;\n }",
" return image2;\n}\n#endif",
"static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n typedef struct {\n unsigned char Type[4];\n unsigned int nRows;\n unsigned int nCols;\n unsigned int imagf;\n unsigned int nameLen;\n } MAT4_HDR;",
" long\n ldblk;",
" EndianType\n endian;",
" Image\n *rotate_image;",
" MagickBooleanType\n status;",
" MAT4_HDR\n HDR;",
" QuantumInfo\n *quantum_info;",
" QuantumFormatType\n format_type;",
" register ssize_t\n i;",
" ssize_t\n count,\n y;",
" unsigned char\n *pixels;",
" unsigned int\n depth;",
"\n quantum_info=(QuantumInfo *) NULL;\n (void) SeekBlob(image,0,SEEK_SET);\n while (EOFBlob(image) != MagickFalse)\n {\n /*\n Object parser loop.\n */\n ldblk=ReadBlobLSBLong(image);\n if ((ldblk > 9999) || (ldblk < 0))\n break;\n HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */\n HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */\n HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */\n HDR.Type[0]=ldblk; /* M digit */\n if (HDR.Type[3] != 0)\n break; /* Data format */\n if (HDR.Type[2] != 0)\n break; /* Always 0 */\n if (HDR.Type[0] == 0)\n {\n HDR.nRows=ReadBlobLSBLong(image);\n HDR.nCols=ReadBlobLSBLong(image);\n HDR.imagf=ReadBlobLSBLong(image);\n HDR.nameLen=ReadBlobLSBLong(image);\n endian=LSBEndian;\n }\n else\n {\n HDR.nRows=ReadBlobMSBLong(image);\n HDR.nCols=ReadBlobMSBLong(image);\n HDR.imagf=ReadBlobMSBLong(image);\n HDR.nameLen=ReadBlobMSBLong(image);\n endian=MSBEndian;\n }\n if ((HDR.imagf != 0) && (HDR.imagf != 1))\n break;\n if (HDR.nameLen > 0xFFFF)\n return((Image *) NULL);\n for (i=0; i < (ssize_t) HDR.nameLen; i++)\n {\n int\n byte;",
" /*\n Skip matrix name.\n */\n byte=ReadBlobByte(image);\n if (byte == EOF)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n }\n image->columns=(size_t) HDR.nRows;\n image->rows=(size_t) HDR.nCols;\n SetImageColorspace(image,GRAYColorspace,exception);\n if (image_info->ping != MagickFalse)\n {\n Swap(image->columns,image->rows);\n return(image);\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return((Image *) NULL);\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n return((Image *) NULL);\n switch(HDR.Type[1])\n {\n case 0:\n format_type=FloatingPointQuantumFormat;\n depth=64;\n break;\n case 1:\n format_type=FloatingPointQuantumFormat;\n depth=32;\n break;\n case 2:\n format_type=UnsignedQuantumFormat;\n depth=16;\n break;\n case 3:\n format_type=SignedQuantumFormat;\n depth=16;\n break;\n case 4:\n format_type=UnsignedQuantumFormat;\n depth=8;\n break;\n default:\n format_type=UnsignedQuantumFormat;\n depth=8;\n break;\n }\n image->depth=depth;\n if (HDR.Type[0] != 0)\n SetQuantumEndian(image,quantum_info,MSBEndian);\n status=SetQuantumFormat(image,quantum_info,format_type);\n status=SetQuantumDepth(image,quantum_info,depth);\n status=SetQuantumEndian(image,quantum_info,endian);\n SetQuantumScale(quantum_info,1.0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n if (count == -1)\n break;\n q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n GrayQuantum,pixels,exception);\n if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))\n FixSignedValues(image,q,(int) image->columns);\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n if (HDR.imagf == 1)\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n /*\n Read complex pixels.\n */\n count=ReadBlob(image,depth/8*image->columns,(char *) pixels);\n if (count == -1)\n break;\n if (HDR.Type[1] == 0)\n InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);\n else\n InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);\n }\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n rotate_image=RotateImage(image,90.0,exception);\n if (rotate_image != (Image *) NULL)\n {\n image=DestroyImage(image);\n image=rotate_image;\n }\n if (EOFBlob(image) != MagickFalse)\n {\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n break;\n }\n /*\n Proceed to next image.\n */\n if (image_info->number_scenes != 0)\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n /*\n Allocate next image structure.\n */\n AcquireNextImage(image_info,image,exception);\n if (GetNextImageInList(image) == (Image *) NULL)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,LoadImagesTag,TellBlob(image),\n GetBlobSize(image));\n if (status == MagickFalse)\n break;\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d M A T L A B i m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadMATImage() reads an MAT X image file and returns it. It\n% allocates the memory necessary for the new Image structure and returns a\n% pointer to the new image.\n%\n% The format of the ReadMATImage method is:\n%\n% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image: Method ReadMATImage returns a pointer to the image after\n% reading. A null image is returned if there is a memory shortage or if\n% the image cannot be read.\n%\n% o image_info: Specifies a pointer to a ImageInfo structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;",
" unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;",
" unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);",
"\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");",
" /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);",
" status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");",
" if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */",
" if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n if (clone_info != (ImageInfo *) NULL)\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }",
" filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */",
" MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;",
" clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif",
" if (MATLAB_HDR.DataType!=miMATRIX)\n {\n clone_info=DestroyImageInfo(clone_info);\n continue; /* skip another objects. */\n }",
" MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);",
" MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;",
" MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);",
"\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default:\n if (clone_info != (ImageInfo *) NULL)\n clone_info=DestroyImageInfo(clone_info);\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }",
" MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);",
" if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");",
" switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }",
" CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);",
" (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */",
" NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }",
"\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n return(DestroyImageList(image));\n }\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");",
" /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));",
" MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }",
" /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;",
"\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }",
" if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:",
"\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/",
" if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }",
" if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }",
" if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }",
" /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;",
" if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */",
" /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;",
" blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }",
"done_reading:",
" if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }",
" /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;",
" /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;",
" if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }",
" if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n }",
" RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:",
"",
" CloseBlob(image);",
"\n {\n Image *p;\n ssize_t scene=0;",
" /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;",
" if (tmp == image2)\n image2=(Image *) NULL;",
" DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }",
" /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }",
" if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if (image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\")\n else\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n return (image);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r M A T I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Method RegisterMATImage adds attributes for the MAT image format to\n% the list of supported formats. The attributes include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterMATImage method is:\n%\n% size_t RegisterMATImage(void)\n%\n*/\nModuleExport size_t RegisterMATImage(void)\n{\n MagickInfo\n *entry;",
" entry=AcquireMagickInfo(\"MAT\",\"MAT\",\"MATLAB level 5 image format\");\n entry->decoder=(DecodeImageHandler *) ReadMATImage;\n entry->encoder=(EncodeImageHandler *) WriteMATImage;\n entry->flags^=CoderBlobSupportFlag;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r M A T I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Method UnregisterMATImage removes format registrations made by the\n% MAT module from the list of supported formats.\n%\n% The format of the UnregisterMATImage method is:\n%\n% UnregisterMATImage(void)\n%\n*/\nModuleExport void UnregisterMATImage(void)\n{\n (void) UnregisterMagickInfo(\"MAT\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e M A T L A B I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Function WriteMATImage writes an Matlab matrix to a file.\n%\n% The format of the WriteMATImage method is:\n%\n% MagickBooleanType WriteMATImage(const ImageInfo *image_info,\n% Image *image,ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: Specifies a pointer to a ImageInfo structure.\n%\n% o image: A pointer to an Image structure.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\nstatic MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n MATLAB_HDR[0x80];",
" MagickBooleanType\n status;",
" MagickOffsetType\n scene;",
" struct tm\n local_time;",
" time_t\n current_time;",
" /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"enter MAT\");\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(MagickFalse);\n image->depth=8;",
" current_time=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(¤t_time,&local_time);\n#else\n (void) memcpy(&local_time,localtime(¤t_time),sizeof(local_time));\n#endif\n (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));\n FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),\n \"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d\",\n OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],\n local_time.tm_mday,local_time.tm_hour,local_time.tm_min,\n local_time.tm_sec,local_time.tm_year+1900);\n MATLAB_HDR[0x7C]=0;\n MATLAB_HDR[0x7D]=1;\n MATLAB_HDR[0x7E]='I';\n MATLAB_HDR[0x7F]='M';\n (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);\n scene=0;\n do\n {\n char\n padding;",
" MagickBooleanType\n is_gray;",
" QuantumInfo\n *quantum_info;",
" size_t\n data_size;",
" unsigned char\n *pixels;",
" unsigned int\n z;",
" (void) TransformImageColorspace(image,sRGBColorspace,exception);\n is_gray=SetImageGray(image,exception);\n z=(is_gray != MagickFalse) ? 0 : 3;",
" /*\n Store MAT header.\n */\n data_size = image->rows * image->columns;\n if (is_gray == MagickFalse)\n data_size*=3;\n padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7;",
" (void) WriteBlobLSBLong(image,miMATRIX);\n (void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+\n ((is_gray != MagickFalse) ? 48 : 56));\n (void) WriteBlobLSBLong(image,0x6); /* 0x88 */\n (void) WriteBlobLSBLong(image,0x8); /* 0x8C */\n (void) WriteBlobLSBLong(image,0x6); /* 0x90 */\n (void) WriteBlobLSBLong(image,0);\n (void) WriteBlobLSBLong(image,0x5); /* 0x98 */\n (void) WriteBlobLSBLong(image,(is_gray != MagickFalse) ? 0x8 : 0xC); /* 0x9C - DimFlag */\n (void) WriteBlobLSBLong(image,(unsigned int) image->rows); /* x: 0xA0 */\n (void) WriteBlobLSBLong(image,(unsigned int) image->columns); /* y: 0xA4 */\n if (is_gray == MagickFalse)\n {\n (void) WriteBlobLSBLong(image,3); /* z: 0xA8 */\n (void) WriteBlobLSBLong(image,0);\n }\n (void) WriteBlobLSBShort(image,1); /* 0xB0 */\n (void) WriteBlobLSBShort(image,1); /* 0xB2 */\n (void) WriteBlobLSBLong(image,'M'); /* 0xB4 */\n (void) WriteBlobLSBLong(image,0x2); /* 0xB8 */\n (void) WriteBlobLSBLong(image,(unsigned int) data_size); /* 0xBC */",
" /*\n Store image data.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n do\n {\n const Quantum\n *p;",
" ssize_t\n y;",
" for (y=0; y < (ssize_t)image->columns; y++)\n {\n p=GetVirtualPixels(image,y,0,1,image->rows,exception);\n if (p == (const Quantum *) NULL)\n break;\n (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,\n z2qtype[z],pixels,exception);\n (void) WriteBlob(image,image->rows,pixels);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n } while (z-- >= 2);\n while (padding-- > 0)\n (void) WriteBlobByte(image,0);\n quantum_info=DestroyQuantumInfo(quantum_info);\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(status);\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1354], "buggy_code_start_loc": [1336], "filenames": ["coders/mat.c"], "fixing_code_end_loc": [1355], "fixing_code_start_loc": [1335], "message": "Use-after-free vulnerability in the DestroyImage function in image.c in ImageMagick before 7.0.6-6 allows remote attackers to cause a denial of service via a crafted file.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "1CC65CC8-1DD1-4576-ABD7-939E3A8DEF50", "versionEndExcluding": "6.9.9-6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "7E545DED-03D1-40A4-83C6-35FE50868C26", "versionEndExcluding": "7.0.6-6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.0-0", "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}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "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:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use-after-free vulnerability in the DestroyImage function in image.c in ImageMagick before 7.0.6-6 allows remote attackers to cause a denial of service via a crafted file."}, {"lang": "es", "value": "Una vulnerabilidad de uso de memoria antes de liberaci\u00f3n (use-after-free)en la funci\u00f3n DestroyImage en image.c de ImageMagick para versiones anteriores a la 7.0.6-6 permite que atacantes remotos provoquen una denegaci\u00f3n de servicio mediante un archivo manipulado."}], "evaluatorComment": null, "id": "CVE-2017-12877", "lastModified": "2021-04-28T18:12:36.983", "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": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-08-28T19:29:00.790", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2017/08/16/2"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory", "VDB Entry"], "url": "https://blogs.gentoo.org/ago/2017/08/10/imagemagick-use-after-free-in-destroyimage-image-c/"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/04178de2247e353fc095846784b9a10fefdbf890"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201711-07"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3681-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2017/dsa-4040"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2017/dsa-4074"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/04178de2247e353fc095846784b9a10fefdbf890"}, "type": "CWE-416"}
| 307
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import asyncio\nimport string\nfrom random import choice\nfrom typing import Optional",
"import discord\nfrom redbot.core import Config, commands\nfrom redbot.core.i18n import Translator, cog_i18n",
"_ = Translator(\"Roomer\", __file__)",
"\n@cog_i18n(_)\nclass Roomer(commands.Cog):",
" __version__ = \"1.0.0\"",
"\n def format_help_for_context(self, ctx: commands.Context) -> str:\n # Thanks Sinbad! And Trusty in whose cogs I found this.\n pre_processed = super().format_help_for_context(ctx)\n return f\"{pre_processed}\\n\\nVersion: {self.__version__}\"",
" async def red_delete_data_for_user(self, **kwargs):\n pass # This cog stores no EUD",
" def __init__(self, bot):\n self.config = Config.get_conf(self, identifier=300620201743, force_registration=True)\n default_guild = {\n \"auto_channels\": None,\n \"name\": \"general\",\n \"auto\": False,\n \"pstart\": None,\n \"pcat\": None,\n \"pchannels\": {},\n \"private\": False,\n \"private_textchannels_enabled\": False,\n \"private_textchannels\": {},\n }\n self.config.register_guild(**default_guild)\n self.config.register_global(notification=0)\n self.invoiceConfig = None\n bot.loop.create_task(self.initialize(bot))",
" async def initialize(self, bot):\n await bot.wait_until_red_ready()\n self._maybe_get_invoice_config(bot)\n await self._send_pending_owner_notifications(bot)",
" # region listeners",
" @commands.Cog.listener()\n async def on_voice_state_update(self, member, before, after):\n settings = await self.config.guild(member.guild).all()\n # Some config cleanup for older versions here\n try:\n if settings[\"category\"]:\n await self.config.guild(member.guild).category.clear()\n except KeyError:\n pass\n await self._autoroom_listener(settings, member, before.channel, after.channel)\n await self._privatevc_listener(settings, member, before.channel)",
" # region autoroom listener",
" async def _autoroom_listener(self, settings, member, before_channel, after_channel):\n if settings[\"auto\"]:\n if settings[\"auto_channels\"]:\n if after_channel:\n await self._member_joined_auto_start_channel(settings, member, after_channel)\n if before_channel:\n await self._maybe_delete_auto_channels(\n settings, member, before_channel, after_channel\n )",
" async def _member_joined_auto_start_channel(self, settings, member, after_channel):\n if after_channel.id in settings[\"auto_channels\"]:\n channel = await after_channel.category.create_voice_channel(\n settings[\"name\"],\n overwrites=after_channel.overwrites,\n reason=_(\"Automated voicechannel creation.\"),\n )\n await member.move_to(channel, reason=_(\"Moved to automatically created channel.\"))",
" async def _maybe_delete_auto_channels(self, settings, member, before_channel, after_channel):\n if len(before_channel.members) == 0:\n auto_categories = [\n member.guild.get_channel(c).category for c in settings[\"auto_channels\"]\n ]\n if before_channel.id in settings[\"auto_channels\"]:\n return\n elif before_channel.category in auto_categories:\n try:\n await before_channel.delete(reason=_(\"Channel empty.\"))\n except discord.NotFound:\n pass",
" # endregion autoroom listener",
" # region privatevc listener",
" async def _privatevc_listener(self, settings, member, before_channel):\n if settings[\"private\"]:\n if before_channel:\n if before_channel.id in settings[\"pchannels\"].values():\n if len(before_channel.members) == 0:\n for key in settings[\"pchannels\"]:\n if settings[\"pchannels\"][key] == before_channel.id:\n ckey = key\n del settings[\"pchannels\"][ckey]\n await self.config.guild(member.guild).pchannels.set(settings[\"pchannels\"])\n await before_channel.delete(reason=_(\"Private room empty.\"))",
" # endregion privatevc listener",
" # endregion listeners",
" @commands.admin()\n @commands.guild_only()\n @commands.group()\n async def roomer(self, ctx):\n \"\"\"Roomer settings\"\"\"\n pass",
" @commands.guild_only()\n @commands.group()\n async def vc(self, ctx):\n \"\"\"Voicechannel commands.\"\"\"\n pass",
" @commands.guild_only()\n @commands.group()\n async def tc(self, ctx):\n \"\"\"Textchannel commands.\"\"\"\n pass",
" # region auto\n @roomer.group()\n async def auto(self, ctx):\n \"\"\"Automation settings.\"\"\"\n pass",
" @auto.command()\n async def enable(self, ctx):\n \"\"\"Enable automatic voicechannel creation.\"\"\"\n await self.config.guild(ctx.guild).auto.set(True)\n await ctx.send(_(\"Automatic voicechannel creation enabled.\"))",
" @auto.command()\n async def disable(self, ctx):\n \"\"\"Disable automatic voicechannel creation.\"\"\"\n await self.config.guild(ctx.guild).auto.set(True)\n await ctx.send(_(\"Automatic voicechannel creation disabled.\"))",
" @auto.command()\n async def name(self, ctx, *, name: str):\n \"\"\"Set the name that is used for automatically created voicechannels.\"\"\"\n await self.config.guild(ctx.guild).name.set(name)\n await ctx.send(\n _(\"Automatically created voicechannels will now be named ``{name}``.\").format(\n name=name\n )\n )",
" @auto.group()\n async def channel(self, ctx):\n \"\"\"Manage channels related to automated voicechannels.\"\"\"\n pass",
" @channel.command()\n async def add(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Add a start channel used for automatic voicechannels.\"\"\"\n if not channel.category:\n return await ctx.send(\n _(\n \"{channel} is not in a discord category. Auto-channels need to be part of a category for this feature to work properly.\"\n ).format(channel=channel.name)\n )\n auto_channels = await self.config.guild(ctx.guild).auto_channels()\n if auto_channels is None:\n auto_channels = []\n auto_channels.append(channel.id)\n await self.config.guild(ctx.guild).auto_channels.set(auto_channels)\n await ctx.send(\n _(\"Startchannel used for automatic voicechannels added: {channel}\").format(\n channel=channel.name\n )\n )",
" @channel.command()\n async def remove(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Remove a start channel used for automatic voicechannels.\"\"\"\n auto_channels = await self.config.guild(ctx.guild).auto_channels()\n auto_channels.remove(channel.id)\n await self.config.guild(ctx.guild).auto_channels.set(auto_channels)\n await ctx.send(\n _(\"Startchannel used for automatic voicechannels removed: {channel}\").format(\n channel=channel.name\n )\n )",
" # endregion auto",
" # region privatevc",
" @roomer.group()\n async def private(self, ctx):\n \"\"\"Change settings for private rooms\"\"\"\n pass",
" @private.command(name=\"enable\")\n async def penable(self, ctx):\n \"\"\"Enable private rooms\"\"\"\n if await self.config.guild(ctx.guild).pstart():\n await self.config.guild(ctx.guild).private.set(True)\n await ctx.send(_(\"Private channels enabled.\"))\n else:\n await ctx.send(\n _(\"Set up a starting channel using {command} first.\").format(\n command=f\"``{ctx.clean_prefix}roomer private startchannel``\"\n )\n )",
" @private.command(name=\"disable\")\n async def pdisable(self, ctx):\n \"\"\"Disable private rooms\"\"\"\n await self.config.guild(ctx.guild).private.set(False)\n await ctx.send(_(\"Private channels disabled.\"))",
" @private.command()\n async def startchannel(self, ctx, vc: discord.VoiceChannel):\n \"\"\"Set a channel that users will join to start using private rooms.\\nI recommend not allowing talking permissions here.\"\"\"\n await self.config.guild(ctx.guild).pstart.set(vc.id)\n await self.config.guild(ctx.guild).pcat.set(vc.category_id)\n await ctx.send(\n _(\n \"Private starting channel set. Users can join this channel to use all features of private rooms.\\nI recommend not allowing members to speak in this channel.\"\n )\n )",
" @commands.max_concurrency(1, commands.BucketType.guild, wait=True)\n @vc.command()\n async def create(self, ctx, public: Optional[bool] = False, *, name: str):\n \"\"\"Create a private voicechannel.\"\"\"\n data = await self.config.guild(ctx.guild).all()\n if data[\"private\"]:\n try:\n if ctx.author.voice.channel.id == data[\"pstart\"]:\n key = await self._generate_key(data[\"pchannels\"].keys())\n if public:\n ov = {\n ctx.author: discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True, manage_channels=True\n )\n }\n else:\n ov = {\n ctx.guild.default_role: discord.PermissionOverwrite(\n view_channel=True,\n connect=False,\n use_voice_activation=True,\n ),\n ctx.author: discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True, manage_channels=True\n ),\n }\n c = await ctx.guild.create_voice_channel(\n name,\n overwrites=ov,\n category=ctx.guild.get_channel(data[\"pcat\"]),\n reason=_(\"Private room\"),\n )\n await ctx.author.move_to(c, reason=_(\"Private channel.\"))\n data[\"pchannels\"][key] = c.id\n await self.config.guild(ctx.guild).pchannels.set(data[\"pchannels\"])\n try:\n await self._send_key(ctx, key)\n except KeyError:\n await ctx.send(\n _(\"Couldn't send the key to your private channel. Aborting...\")\n )\n await ctx.autho.move_to(ctx.author.voice.channel)\n await c.delete()\n return\n else:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n except AttributeError:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n else:\n await ctx.send(_(\"Private rooms are not enabled on this server.\"))",
" @commands.guild_only()\n @vc.command()\n async def join(self, ctx, key: str):\n \"\"\"Join a private room.\"\"\"\n await ctx.message.delete()\n async with ctx.typing():\n data = await self.config.guild(ctx.guild).all()\n if data[\"private\"]:\n try:\n if ctx.author.voice.channel.id == data[\"pstart\"]:\n if key in data[\"pchannels\"]:\n await ctx.author.move_to(ctx.guild.get_channel(data[\"pchannels\"][key]))\n else:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n except AttributeError:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n else:\n await ctx.send(_(\"Private rooms are not enabled on this server.\"))",
" @commands.guild_only()\n @vc.command()\n async def hidden(self, ctx: commands.Context, true_or_false: Optional[bool] = True):\n \"\"\"Hide or unhide a voicechannel you own.\"\"\"\n data = await self.config.guild(ctx.guild).pchannels()\n try:\n for key in data:\n if data[key] == ctx.author.voice.channel.id:",
" ov = {\n ctx.guild.default_role: discord.PermissionOverwrite(\n view_channel=False, connect=False\n ),\n ctx.author: discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True, manage_channels=True\n ),\n }",
" if self.invoiceConfig:\n ov[\n ctx.guild.get_role(\n await self.invoiceConfig.channel(ctx.author.voice.channel).role()\n )\n ] = discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True\n )\n await ctx.author.voice.channel.edit(overwrites=ov)\n await ctx.tick()\n await ctx.send(_(\"VC has been hidden successfully.\"))\n except AttributeError:\n return await ctx.send(_(\"You need to be in a VC to do this.\"))",
" async def _send_key(self, ctx, key):\n text = _(\n \"The key to your private room is: ``{key}``\\nGive this key to a friend and ask them to use ``{command}`` to join your private room.\"\n ).format(key=key, command=f\"{ctx.clean_prefix}vc join {key}\")\n if self.invoiceConfig:\n for i in range(10):\n try:\n await ctx.guild.get_channel(\n await self.invoiceConfig.channel(ctx.author.voice.channel).channel()\n ).send(text)\n break\n except:\n await asyncio.sleep(2)\n if i == 9:\n await self._send_key_dm(ctx.author, text)\n else:\n await self._send_key_dm(ctx.author, text)",
" async def _send_key_dm(self, author, text):\n try:\n await author.send(text)\n except discord.Forbidden:\n raise KeyError",
" # endregion privatevc",
" # region privatetc",
" @roomer.group()\n async def text(self, ctx):\n \"\"\"Change settings for private text channels.\"\"\"\n pass",
" @text.command(name=\"enable\")\n async def tc_enable(self, ctx):\n \"\"\"Enable private text channels.\"\"\"\n await self.config.guild(ctx.guild).private_textchannels_enabled.set(True)\n await ctx.send(_(\"Private text channels enabled.\"))",
" @text.command(name=\"disable\")\n async def tc_disable(self, ctx):\n \"\"\"Enable private text channels.\"\"\"\n await self.config.guild(ctx.guild).private_textchannels_enabled.set(False)\n await ctx.send(_(\"Private text channels disabled.\"))",
" @commands.max_concurrency(1, commands.BucketType.guild, wait=True)\n @tc.command(name=\"create\")\n async def tc_create(self, ctx, public: Optional[bool] = False, *, name: str):\n \"\"\"Create a private text channel.\"\"\"\n data = await self.config.guild(ctx.guild).all()\n if data[\"private_textchannels_enabled\"]:\n key = await self._generate_key(data[\"private_textchannels\"].keys())\n ov = {\n ctx.guild.default_role: discord.PermissionOverwrite(\n view_channel=False,\n read_message_history=False,\n read_messages=False,\n send_messages=False,\n ),\n ctx.author: discord.PermissionOverwrite(\n view_channel=True,\n manage_channels=True,\n manage_messages=True,\n read_message_history=True,\n read_messages=True,\n send_messages=True,\n send_tts_messages=True,\n ),\n }\n c = await ctx.guild.create_text_channel(\n name,\n overwrites=ov,\n category=ctx.guild.get_channel(data[\"pcat\"]),\n reason=_(\"Private text channel\"),\n )\n data[\"private_textchannels\"][key] = c.id\n await self.config.guild(ctx.guild).pchannels.set(data[\"private_textchannels\"])\n await self._send_private_textchannel_key(c, key, ctx.clean_prefix)\n else:\n await ctx.send(_(\"Private text channels are not enabled on this server.\"))",
" @commands.max_concurrency(1, commands.BucketType.guild, wait=True)\n @tc.command(name=\"close\")\n async def tc_close(self, ctx):\n \"\"\"Close the current private text cannel.\"\"\"\n async with self.config.guild(ctx.guild).private_textchannels() as textchannels:\n if ctx.channel.id in textchannels:\n await ctx.channel.delete(reason=_(\"Private text channel deleted.\"))\n del textchannels[ctx.channel.id]\n else:\n await ctx.send(_(\"Use this command in a private text channel.\"))",
" @tc.command(name=\"join\")\n async def tc_join(self, ctx, key: str):\n \"\"\"Join a private text channel.\"\"\"\n await ctx.message.delete()\n async with ctx.typing():\n data = await self.config.guild(ctx.guild).all()\n if data[\"private_textchannels_enabled\"]:\n if key in data[\"private_textchannels\"]:\n await ctx.guild.get_channel(int(key)).set_permissions(\n ctx.author,\n read_message_history=True,\n read_messages=True,\n send_messages=True,\n view_channel=True,\n )\n else:\n await ctx.send(_(\"Private rooms are not enabled on this server.\"))",
" async def _send_private_textchannel_key(\n self, channel: discord.TextChannel, key: str, clean_prefix\n ):\n m = await channel.send(\n _(\n \"The key to this private text channel is: ``{key}``\\nGive this key to a friend and ask them to use ``{command}`` to join your private room.\"\n ).format(key=key, command=f\"{clean_prefix}tc join {key}\")\n )\n try:\n await m.pin()\n except discord.Forbidden:\n pass",
" # endregion privatetc",
" # region helpers\n async def sendNotInStartChannelMessage(self, ctx, channel_id):\n await ctx.send(\n _(\"You must be in the voicechannel {vc} first.\").format(\n vc=ctx.guild.get_channel(channel_id).mention\n )\n )",
" def _maybe_get_invoice_config(self, bot):\n if bot.get_cog(\"InVoice\"):\n self.invoiceConfig = bot.get_cog(\"InVoice\").config",
" async def _send_pending_owner_notifications(self, bot):\n if await self.config.notification() == 0:\n await bot.send_to_owners(\n \"Roomer: If you are updating roomer you will need to redo your autoroom setup.\\n\\nThis is due to some backend storage changes to allow for multiple automated categories.\"\n )\n await self.config.notification.set(1)",
" async def _generate_key(self, key_list_for_channel_type):\n while True:\n # This probably won't turn into an endless loop bceause it has more possibilities than discord allows channels per guild\n key = \"\".join(choice(string.ascii_lowercase + \"0123456789\") for i in range(16))\n if not (key in key_list_for_channel_type):\n return key",
" # endregion helpers"
] |
[
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [325], "buggy_code_start_loc": [15], "filenames": ["roomer/roomer.py"], "fixing_code_end_loc": [321], "fixing_code_start_loc": [15], "message": "Roomer is a discord bot cog (extension) which provides automatic voice channel generation as well as private voice and text channels. A vulnerability has been discovered allowing discord users to get the ``manage channel`` permissions in a private VC they have joined. This allowed them to make changes to or delete the voice channel they have taken over. The exploit does not allow access or control to any other channels in the server. Upgrade to version 1.0.1 for a patched version of the cog. As a workaround you may disable private VCs in your guild(server) or unload the roomer cog to render the exploit unusable.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dav-cogs_project:dav-cogs:*:*:*:*:*:*:*:*", "matchCriteriaId": "E33CBB67-F1C1-4F77-8886-644206CB57F0", "versionEndExcluding": "1.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roomer is a discord bot cog (extension) which provides automatic voice channel generation as well as private voice and text channels. A vulnerability has been discovered allowing discord users to get the ``manage channel`` permissions in a private VC they have joined. This allowed them to make changes to or delete the voice channel they have taken over. The exploit does not allow access or control to any other channels in the server. Upgrade to version 1.0.1 for a patched version of the cog. As a workaround you may disable private VCs in your guild(server) or unload the roomer cog to render the exploit unusable."}, {"lang": "es", "value": "Roomer es un bot cog (extensi\u00f3n) de discord que proporciona generaci\u00f3n autom\u00e1tica de canales de voz, as\u00ed como canales privados de voz y texto. Ha sido detectada una vulnerabilidad que permite a usuarios de discord obtener los permisos de \"manage channel\" en un VC privado al que se han unido. Esto les permiti\u00f3 realizar cambios o eliminar el canal de voz que han asumido. La explotaci\u00f3n no permite el acceso ni el control a ning\u00fan otro canal del servidor. Actualizar a versi\u00f3n 1.0.1 para obtener una versi\u00f3n parcheada del cog. Como soluci\u00f3n alternativa, puede desencadenar los VC privados en su guild(server) o descargar el engranaje m\u00e1s espacioso para inutilizar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-32646", "lastModified": "2022-07-02T20:01:19.470", "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": "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": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-05-28T18:15:07.493", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dav-Git/Dav-Cogs/commit/fbe2ae8ec851a2e9e3e2370db3b812f268e8c8cb"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dav-Git/Dav-Cogs/security/advisories/GHSA-3f73-8j6q-28v8"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Dav-Git/Dav-Cogs/commit/fbe2ae8ec851a2e9e3e2370db3b812f268e8c8cb"}, "type": "NVD-CWE-noinfo"}
| 308
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import asyncio\nimport string\nfrom random import choice\nfrom typing import Optional",
"import discord\nfrom redbot.core import Config, commands\nfrom redbot.core.i18n import Translator, cog_i18n",
"_ = Translator(\"Roomer\", __file__)",
"\n@cog_i18n(_)\nclass Roomer(commands.Cog):",
" __version__ = \"1.0.1\"",
"\n def format_help_for_context(self, ctx: commands.Context) -> str:\n # Thanks Sinbad! And Trusty in whose cogs I found this.\n pre_processed = super().format_help_for_context(ctx)\n return f\"{pre_processed}\\n\\nVersion: {self.__version__}\"",
" async def red_delete_data_for_user(self, **kwargs):\n pass # This cog stores no EUD",
" def __init__(self, bot):\n self.config = Config.get_conf(self, identifier=300620201743, force_registration=True)\n default_guild = {\n \"auto_channels\": None,\n \"name\": \"general\",\n \"auto\": False,\n \"pstart\": None,\n \"pcat\": None,\n \"pchannels\": {},\n \"private\": False,\n \"private_textchannels_enabled\": False,\n \"private_textchannels\": {},\n }\n self.config.register_guild(**default_guild)\n self.config.register_global(notification=0)\n self.invoiceConfig = None\n bot.loop.create_task(self.initialize(bot))",
" async def initialize(self, bot):\n await bot.wait_until_red_ready()\n self._maybe_get_invoice_config(bot)\n await self._send_pending_owner_notifications(bot)",
" # region listeners",
" @commands.Cog.listener()\n async def on_voice_state_update(self, member, before, after):\n settings = await self.config.guild(member.guild).all()\n # Some config cleanup for older versions here\n try:\n if settings[\"category\"]:\n await self.config.guild(member.guild).category.clear()\n except KeyError:\n pass\n await self._autoroom_listener(settings, member, before.channel, after.channel)\n await self._privatevc_listener(settings, member, before.channel)",
" # region autoroom listener",
" async def _autoroom_listener(self, settings, member, before_channel, after_channel):\n if settings[\"auto\"]:\n if settings[\"auto_channels\"]:\n if after_channel:\n await self._member_joined_auto_start_channel(settings, member, after_channel)\n if before_channel:\n await self._maybe_delete_auto_channels(\n settings, member, before_channel, after_channel\n )",
" async def _member_joined_auto_start_channel(self, settings, member, after_channel):\n if after_channel.id in settings[\"auto_channels\"]:\n channel = await after_channel.category.create_voice_channel(\n settings[\"name\"],\n overwrites=after_channel.overwrites,\n reason=_(\"Automated voicechannel creation.\"),\n )\n await member.move_to(channel, reason=_(\"Moved to automatically created channel.\"))",
" async def _maybe_delete_auto_channels(self, settings, member, before_channel, after_channel):\n if len(before_channel.members) == 0:\n auto_categories = [\n member.guild.get_channel(c).category for c in settings[\"auto_channels\"]\n ]\n if before_channel.id in settings[\"auto_channels\"]:\n return\n elif before_channel.category in auto_categories:\n try:\n await before_channel.delete(reason=_(\"Channel empty.\"))\n except discord.NotFound:\n pass",
" # endregion autoroom listener",
" # region privatevc listener",
" async def _privatevc_listener(self, settings, member, before_channel):\n if settings[\"private\"]:\n if before_channel:\n if before_channel.id in settings[\"pchannels\"].values():\n if len(before_channel.members) == 0:\n for key in settings[\"pchannels\"]:\n if settings[\"pchannels\"][key] == before_channel.id:\n ckey = key\n del settings[\"pchannels\"][ckey]\n await self.config.guild(member.guild).pchannels.set(settings[\"pchannels\"])\n await before_channel.delete(reason=_(\"Private room empty.\"))",
" # endregion privatevc listener",
" # endregion listeners",
" @commands.admin()\n @commands.guild_only()\n @commands.group()\n async def roomer(self, ctx):\n \"\"\"Roomer settings\"\"\"\n pass",
" @commands.guild_only()\n @commands.group()\n async def vc(self, ctx):\n \"\"\"Voicechannel commands.\"\"\"\n pass",
" @commands.guild_only()\n @commands.group()\n async def tc(self, ctx):\n \"\"\"Textchannel commands.\"\"\"\n pass",
" # region auto\n @roomer.group()\n async def auto(self, ctx):\n \"\"\"Automation settings.\"\"\"\n pass",
" @auto.command()\n async def enable(self, ctx):\n \"\"\"Enable automatic voicechannel creation.\"\"\"\n await self.config.guild(ctx.guild).auto.set(True)\n await ctx.send(_(\"Automatic voicechannel creation enabled.\"))",
" @auto.command()\n async def disable(self, ctx):\n \"\"\"Disable automatic voicechannel creation.\"\"\"\n await self.config.guild(ctx.guild).auto.set(True)\n await ctx.send(_(\"Automatic voicechannel creation disabled.\"))",
" @auto.command()\n async def name(self, ctx, *, name: str):\n \"\"\"Set the name that is used for automatically created voicechannels.\"\"\"\n await self.config.guild(ctx.guild).name.set(name)\n await ctx.send(\n _(\"Automatically created voicechannels will now be named ``{name}``.\").format(\n name=name\n )\n )",
" @auto.group()\n async def channel(self, ctx):\n \"\"\"Manage channels related to automated voicechannels.\"\"\"\n pass",
" @channel.command()\n async def add(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Add a start channel used for automatic voicechannels.\"\"\"\n if not channel.category:\n return await ctx.send(\n _(\n \"{channel} is not in a discord category. Auto-channels need to be part of a category for this feature to work properly.\"\n ).format(channel=channel.name)\n )\n auto_channels = await self.config.guild(ctx.guild).auto_channels()\n if auto_channels is None:\n auto_channels = []\n auto_channels.append(channel.id)\n await self.config.guild(ctx.guild).auto_channels.set(auto_channels)\n await ctx.send(\n _(\"Startchannel used for automatic voicechannels added: {channel}\").format(\n channel=channel.name\n )\n )",
" @channel.command()\n async def remove(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Remove a start channel used for automatic voicechannels.\"\"\"\n auto_channels = await self.config.guild(ctx.guild).auto_channels()\n auto_channels.remove(channel.id)\n await self.config.guild(ctx.guild).auto_channels.set(auto_channels)\n await ctx.send(\n _(\"Startchannel used for automatic voicechannels removed: {channel}\").format(\n channel=channel.name\n )\n )",
" # endregion auto",
" # region privatevc",
" @roomer.group()\n async def private(self, ctx):\n \"\"\"Change settings for private rooms\"\"\"\n pass",
" @private.command(name=\"enable\")\n async def penable(self, ctx):\n \"\"\"Enable private rooms\"\"\"\n if await self.config.guild(ctx.guild).pstart():\n await self.config.guild(ctx.guild).private.set(True)\n await ctx.send(_(\"Private channels enabled.\"))\n else:\n await ctx.send(\n _(\"Set up a starting channel using {command} first.\").format(\n command=f\"``{ctx.clean_prefix}roomer private startchannel``\"\n )\n )",
" @private.command(name=\"disable\")\n async def pdisable(self, ctx):\n \"\"\"Disable private rooms\"\"\"\n await self.config.guild(ctx.guild).private.set(False)\n await ctx.send(_(\"Private channels disabled.\"))",
" @private.command()\n async def startchannel(self, ctx, vc: discord.VoiceChannel):\n \"\"\"Set a channel that users will join to start using private rooms.\\nI recommend not allowing talking permissions here.\"\"\"\n await self.config.guild(ctx.guild).pstart.set(vc.id)\n await self.config.guild(ctx.guild).pcat.set(vc.category_id)\n await ctx.send(\n _(\n \"Private starting channel set. Users can join this channel to use all features of private rooms.\\nI recommend not allowing members to speak in this channel.\"\n )\n )",
" @commands.max_concurrency(1, commands.BucketType.guild, wait=True)\n @vc.command()\n async def create(self, ctx, public: Optional[bool] = False, *, name: str):\n \"\"\"Create a private voicechannel.\"\"\"\n data = await self.config.guild(ctx.guild).all()\n if data[\"private\"]:\n try:\n if ctx.author.voice.channel.id == data[\"pstart\"]:\n key = await self._generate_key(data[\"pchannels\"].keys())\n if public:\n ov = {\n ctx.author: discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True, manage_channels=True\n )\n }\n else:\n ov = {\n ctx.guild.default_role: discord.PermissionOverwrite(\n view_channel=True,\n connect=False,\n use_voice_activation=True,\n ),\n ctx.author: discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True, manage_channels=True\n ),\n }\n c = await ctx.guild.create_voice_channel(\n name,\n overwrites=ov,\n category=ctx.guild.get_channel(data[\"pcat\"]),\n reason=_(\"Private room\"),\n )\n await ctx.author.move_to(c, reason=_(\"Private channel.\"))\n data[\"pchannels\"][key] = c.id\n await self.config.guild(ctx.guild).pchannels.set(data[\"pchannels\"])\n try:\n await self._send_key(ctx, key)\n except KeyError:\n await ctx.send(\n _(\"Couldn't send the key to your private channel. Aborting...\")\n )\n await ctx.autho.move_to(ctx.author.voice.channel)\n await c.delete()\n return\n else:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n except AttributeError:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n else:\n await ctx.send(_(\"Private rooms are not enabled on this server.\"))",
" @commands.guild_only()\n @vc.command()\n async def join(self, ctx, key: str):\n \"\"\"Join a private room.\"\"\"\n await ctx.message.delete()\n async with ctx.typing():\n data = await self.config.guild(ctx.guild).all()\n if data[\"private\"]:\n try:\n if ctx.author.voice.channel.id == data[\"pstart\"]:\n if key in data[\"pchannels\"]:\n await ctx.author.move_to(ctx.guild.get_channel(data[\"pchannels\"][key]))\n else:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n except AttributeError:\n await self.sendNotInStartChannelMessage(ctx, data[\"pstart\"])\n else:\n await ctx.send(_(\"Private rooms are not enabled on this server.\"))",
" @commands.guild_only()\n @vc.command()\n async def hidden(self, ctx: commands.Context, true_or_false: Optional[bool] = True):\n \"\"\"Hide or unhide a voicechannel you own.\"\"\"\n data = await self.config.guild(ctx.guild).pchannels()\n try:\n for key in data:\n if data[key] == ctx.author.voice.channel.id:",
" ov = ctx.author.voice.channel.overwrites\n ov[ctx.guild.default_role] = discord.PermissionOverwrite(\n view_channel=False, connect=False\n )",
" if self.invoiceConfig:\n ov[\n ctx.guild.get_role(\n await self.invoiceConfig.channel(ctx.author.voice.channel).role()\n )\n ] = discord.PermissionOverwrite(\n view_channel=True, connect=True, speak=True\n )\n await ctx.author.voice.channel.edit(overwrites=ov)\n await ctx.tick()\n await ctx.send(_(\"VC has been hidden successfully.\"))\n except AttributeError:\n return await ctx.send(_(\"You need to be in a VC to do this.\"))",
" async def _send_key(self, ctx, key):\n text = _(\n \"The key to your private room is: ``{key}``\\nGive this key to a friend and ask them to use ``{command}`` to join your private room.\"\n ).format(key=key, command=f\"{ctx.clean_prefix}vc join {key}\")\n if self.invoiceConfig:\n for i in range(10):\n try:\n await ctx.guild.get_channel(\n await self.invoiceConfig.channel(ctx.author.voice.channel).channel()\n ).send(text)\n break\n except:\n await asyncio.sleep(2)\n if i == 9:\n await self._send_key_dm(ctx.author, text)\n else:\n await self._send_key_dm(ctx.author, text)",
" async def _send_key_dm(self, author, text):\n try:\n await author.send(text)\n except discord.Forbidden:\n raise KeyError",
" # endregion privatevc",
" # region privatetc",
" @roomer.group()\n async def text(self, ctx):\n \"\"\"Change settings for private text channels.\"\"\"\n pass",
" @text.command(name=\"enable\")\n async def tc_enable(self, ctx):\n \"\"\"Enable private text channels.\"\"\"\n await self.config.guild(ctx.guild).private_textchannels_enabled.set(True)\n await ctx.send(_(\"Private text channels enabled.\"))",
" @text.command(name=\"disable\")\n async def tc_disable(self, ctx):\n \"\"\"Enable private text channels.\"\"\"\n await self.config.guild(ctx.guild).private_textchannels_enabled.set(False)\n await ctx.send(_(\"Private text channels disabled.\"))",
" @commands.max_concurrency(1, commands.BucketType.guild, wait=True)\n @tc.command(name=\"create\")\n async def tc_create(self, ctx, public: Optional[bool] = False, *, name: str):\n \"\"\"Create a private text channel.\"\"\"\n data = await self.config.guild(ctx.guild).all()\n if data[\"private_textchannels_enabled\"]:\n key = await self._generate_key(data[\"private_textchannels\"].keys())\n ov = {\n ctx.guild.default_role: discord.PermissionOverwrite(\n view_channel=False,\n read_message_history=False,\n read_messages=False,\n send_messages=False,\n ),\n ctx.author: discord.PermissionOverwrite(\n view_channel=True,\n manage_channels=True,\n manage_messages=True,\n read_message_history=True,\n read_messages=True,\n send_messages=True,\n send_tts_messages=True,\n ),\n }\n c = await ctx.guild.create_text_channel(\n name,\n overwrites=ov,\n category=ctx.guild.get_channel(data[\"pcat\"]),\n reason=_(\"Private text channel\"),\n )\n data[\"private_textchannels\"][key] = c.id\n await self.config.guild(ctx.guild).pchannels.set(data[\"private_textchannels\"])\n await self._send_private_textchannel_key(c, key, ctx.clean_prefix)\n else:\n await ctx.send(_(\"Private text channels are not enabled on this server.\"))",
" @commands.max_concurrency(1, commands.BucketType.guild, wait=True)\n @tc.command(name=\"close\")\n async def tc_close(self, ctx):\n \"\"\"Close the current private text cannel.\"\"\"\n async with self.config.guild(ctx.guild).private_textchannels() as textchannels:\n if ctx.channel.id in textchannels:\n await ctx.channel.delete(reason=_(\"Private text channel deleted.\"))\n del textchannels[ctx.channel.id]\n else:\n await ctx.send(_(\"Use this command in a private text channel.\"))",
" @tc.command(name=\"join\")\n async def tc_join(self, ctx, key: str):\n \"\"\"Join a private text channel.\"\"\"\n await ctx.message.delete()\n async with ctx.typing():\n data = await self.config.guild(ctx.guild).all()\n if data[\"private_textchannels_enabled\"]:\n if key in data[\"private_textchannels\"]:\n await ctx.guild.get_channel(int(key)).set_permissions(\n ctx.author,\n read_message_history=True,\n read_messages=True,\n send_messages=True,\n view_channel=True,\n )\n else:\n await ctx.send(_(\"Private rooms are not enabled on this server.\"))",
" async def _send_private_textchannel_key(\n self, channel: discord.TextChannel, key: str, clean_prefix\n ):\n m = await channel.send(\n _(\n \"The key to this private text channel is: ``{key}``\\nGive this key to a friend and ask them to use ``{command}`` to join your private room.\"\n ).format(key=key, command=f\"{clean_prefix}tc join {key}\")\n )\n try:\n await m.pin()\n except discord.Forbidden:\n pass",
" # endregion privatetc",
" # region helpers\n async def sendNotInStartChannelMessage(self, ctx, channel_id):\n await ctx.send(\n _(\"You must be in the voicechannel {vc} first.\").format(\n vc=ctx.guild.get_channel(channel_id).mention\n )\n )",
" def _maybe_get_invoice_config(self, bot):\n if bot.get_cog(\"InVoice\"):\n self.invoiceConfig = bot.get_cog(\"InVoice\").config",
" async def _send_pending_owner_notifications(self, bot):\n if await self.config.notification() == 0:\n await bot.send_to_owners(\n \"Roomer: If you are updating roomer you will need to redo your autoroom setup.\\n\\nThis is due to some backend storage changes to allow for multiple automated categories.\"\n )\n await self.config.notification.set(1)",
" async def _generate_key(self, key_list_for_channel_type):\n while True:\n # This probably won't turn into an endless loop bceause it has more possibilities than discord allows channels per guild\n key = \"\".join(choice(string.ascii_lowercase + \"0123456789\") for i in range(16))\n if not (key in key_list_for_channel_type):\n return key",
" # endregion helpers"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [325], "buggy_code_start_loc": [15], "filenames": ["roomer/roomer.py"], "fixing_code_end_loc": [321], "fixing_code_start_loc": [15], "message": "Roomer is a discord bot cog (extension) which provides automatic voice channel generation as well as private voice and text channels. A vulnerability has been discovered allowing discord users to get the ``manage channel`` permissions in a private VC they have joined. This allowed them to make changes to or delete the voice channel they have taken over. The exploit does not allow access or control to any other channels in the server. Upgrade to version 1.0.1 for a patched version of the cog. As a workaround you may disable private VCs in your guild(server) or unload the roomer cog to render the exploit unusable.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dav-cogs_project:dav-cogs:*:*:*:*:*:*:*:*", "matchCriteriaId": "E33CBB67-F1C1-4F77-8886-644206CB57F0", "versionEndExcluding": "1.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Roomer is a discord bot cog (extension) which provides automatic voice channel generation as well as private voice and text channels. A vulnerability has been discovered allowing discord users to get the ``manage channel`` permissions in a private VC they have joined. This allowed them to make changes to or delete the voice channel they have taken over. The exploit does not allow access or control to any other channels in the server. Upgrade to version 1.0.1 for a patched version of the cog. As a workaround you may disable private VCs in your guild(server) or unload the roomer cog to render the exploit unusable."}, {"lang": "es", "value": "Roomer es un bot cog (extensi\u00f3n) de discord que proporciona generaci\u00f3n autom\u00e1tica de canales de voz, as\u00ed como canales privados de voz y texto. Ha sido detectada una vulnerabilidad que permite a usuarios de discord obtener los permisos de \"manage channel\" en un VC privado al que se han unido. Esto les permiti\u00f3 realizar cambios o eliminar el canal de voz que han asumido. La explotaci\u00f3n no permite el acceso ni el control a ning\u00fan otro canal del servidor. Actualizar a versi\u00f3n 1.0.1 para obtener una versi\u00f3n parcheada del cog. Como soluci\u00f3n alternativa, puede desencadenar los VC privados en su guild(server) o descargar el engranaje m\u00e1s espacioso para inutilizar la explotaci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-32646", "lastModified": "2022-07-02T20:01:19.470", "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": "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": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-05-28T18:15:07.493", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dav-Git/Dav-Cogs/commit/fbe2ae8ec851a2e9e3e2370db3b812f268e8c8cb"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dav-Git/Dav-Cogs/security/advisories/GHSA-3f73-8j6q-28v8"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-287"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Dav-Git/Dav-Cogs/commit/fbe2ae8ec851a2e9e3e2370db3b812f268e8c8cb"}, "type": "NVD-CWE-noinfo"}
| 308
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# WP-UserOnline\nContributors: GamerZ \nDonate link: https://lesterchan.net/site/donation/ \nTags: useronline, usersonline, wp-useronline, online, users, user, ajax, widget \nRequires at least: 4.0 \nTested up to: 6.0 ",
"Stable tag: 2.88.0 ",
"License: GPLv2 or later \nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html ",
"Enable you to display how many users are online on your Wordpress blog with detailed statistics.",
"## Description\nThis plugin enables you to display how many users are online on your Wordpress site, with detailed statistics of where they are and who they are (Members/Guests/Search Bots).",
"### Usage (With Widget)\n1. Go to `WP-Admin -> Appearance -> Widgets`\n1. The widget name is <strong>UserOnline</strong>.\n1. Scroll down for instructions on how to create a *UserOnline Page*.",
"### Usage (Without Widget)\n* Open `wp-content/themes/<YOUR THEME NAME>/sidebar.php` and add Anywhere:",
"```php\n<?php if (function_exists('users_online')): ?>\n\t<p>Users online: <div id=\"useronline-count\"><?php users_online(); ?></div></p>\n<?php endif; ?>\n```",
"### Build Status\n[](https://travis-ci.org/lesterchan/wp-useronline)",
"### Development\n[https://github.com/lesterchan/wp-useronline](https://github.com/lesterchan/wp-useronline \"https://github.com/lesterchan/wp-useronline\")",
"### Credits\n* Plugin icon by [Freepik](http://www.freepik.com) from [Flaticon](http://www.flaticon.com)",
"### Donations\nI spent most of my free time creating, updating, maintaining and supporting these plugins, if you really love my plugins and could spare me a couple of bucks, I will really appreciate it. If not feel free to use it without any obligations.",
"## Screenshots",
"1. Admin - Dashboard's Right Now\n2. UserOnline Page\n3. Admin - Settings Page",
"## Frequently Asked Questions",
"### Creating A UserOnline Page\n1. Go to `WP-Admin -> Pages -> Add New`\n1. Type any title you like in the post's title area\n1. If you ARE using nice permalinks, after typing the title, WordPress will generate the permalink to the page. You will see an 'Edit' link just beside the permalink.\n1. Click 'Edit' and type in `useronline` in the text field and click 'Save'.\n1. Type `[page_useronline]` in the post's content area\n1. Click 'Publish'",
"If you ARE NOT using nice permalinks, you need to go to `WP-Admin -> Settings -> UserOnline` and under 'UserOnline URL', you need to fill in the URL to the UserOnline Page you created above.",
"### To Display Most Number Of Users Online\n* Use:\n```php\n<?php if (function_exists('get_most_users_online')): ?>\n <p>Most Users Ever Online Is <?php echo get_most_users_online(); ?> On <?php echo get_most_users_online_date(); ?></p>\n<?php endif; ?>\n```",
"### To Display Users Browsing Site\n* Use:\n```php\n<?php if (function_exists('get_users_browsing_site')): ?>\n <div id=\"useronline-browsing-site\"><?php echo get_users_browsing_site(); ?></div>\n<?php endif; ?>\n```",
"### To Display Users Browsing A Page\n* Use:\n```php\n<?php if (function_exists('get_users_browsing_page')): ?>\n <div id=\"useronline-browsing-page\"><?php echo get_users_browsing_page(); ?></div>\n<?php endif; ?>\n```",
"### Error on activation: \"Parse error: syntax error, unexpected...\"",
"Make sure your host is running PHP 5. The only foolproof way to do this is to add this line to wp-config.php (after the opening `<?php` tag):",
"`var_dump(PHP_VERSION);`",
"## Changelog",
"",
"### 2.88.0\n* NEW: Bump to WordPress 6.0.\n* FIXED: Fixed XSS. Props @steffinstanly.",
"### 2.85.6\n* NEW: Bump to WordPress 5.6\n* NEW: Added more bots\n* NEW: Remove hardcoded Archive text in page title\n* FIXED: Update SCB Framework to support PHP 8",
"### 2.85.5\n* NEW: Bump to WordPress 5.4\n* NEW: Added more bots",
"### 2.87.4\n* NEW: Bump to WordPress 5.3\n* NEW: Added more bots\n* FIXED: Update SCB Framework To Remove contextual_help",
"### 2.87.3\n* FIXED: Duplicated Settings Saved admin_notices\n* FIXED: Missing arrow\n* FIXED: Updated bots list",
"### 2.87.2\n* NEW: Bump to 4.9\n* FIXED: Notices in SCB Framework",
"### 2.87.1\n* NEW: Bump to 4.7\n* NEW: New useronline_custom_template filter",
"### 2.87\n* NEW: Remove po/mo files from the plugin\n* NEW: Use translate.wordpress.org to translate the plugin\n* FIXED: Update SCB Framework\n* FIXED: Incompatible scbAdminPage::validate()",
"### 2.86\n* FIXED: Notices in Widget Constructor for WordPress 4.3",
"### 2.85\n* NEW: Uses WordPress native uninstall.php",
"### 2.84\n* NEW: Bump to 4.0",
"### 2.83\n* Show user agent when hovering over IP, instead of address lookup\n* Use local time for UserOnline Page\n* Fixed 'Strict Standards: Non-static method' warnings\n* Update scb Framework",
"### 2.82\n* show most recent visitors first\n* fix duplicate entry errors\n* fix ajax requests for SSL",
"### 2.81\n* fixed settings page\n* fixed \"Return to default\" buttons\n* show user list in admin only to users with 'manage_options' capability\n* added 'useronline_bots' filter",
"### 2.80\n* don't show url and referral links for users in the admin area\n* smarter detection via ajax requests\n* fix SQL errors",
"### 2.72\n* fix fatal error on upgrade",
"### 2.71\n* fix %USERONLINE_COUNT% problem",
"### 2.70\n* added option to link user names to their author page\n* allow displaying online users from a different page than the current page\n* bundle language files\n* [more info](http://scribu.net/wordpress/wp-useronline/wu-2-70.html)",
"### 2.62 (2010-03-07)\n* fix integration with WP-Stats\n* fix error with get_admin_page_title()"
] |
[
1,
0,
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": [90, 210, 7], "buggy_code_start_loc": [7, 68, 6], "filenames": ["README.md", "admin.php", "wp-useronline.php"], "fixing_code_end_loc": [94, 220, 7], "fixing_code_start_loc": [7, 68, 6], "message": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wp-useronline_project:wp-useronline:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "18214189-9B13-4D53-ACE3-8213B73CF4F2", "versionEndExcluding": null, "versionEndIncluding": "2.88.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled."}, {"lang": "es", "value": "El plugin WP-UserOnline para WordPress presenta m\u00faltiples vulnerabilidades de tipo Cross-Site Scripting Almacenado en versiones hasta 2.88.0 incluy\u00e9ndola. Esto es debido a que todos los campos de la secci\u00f3n \"Naming Conventions\" no sanean apropiadamente la entrada del usuario, ni la escapan en la salida. Esto hace posible a atacantes autenticados, con privilegios administrativos, inyectar c\u00f3digo JavaScript en la configuraci\u00f3n que es ejecutada cada vez que un usuario acceda a la p\u00e1gina inyectada. Esto s\u00f3lo afecta a las instalaciones multisitio y a las instalaciones en las que se ha desactivado unfiltered_html.\n"}], "evaluatorComment": null, "id": "CVE-2022-2941", "lastModified": "2022-10-01T02:16:20.627", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security@wordfence.com", "type": "Secondary"}]}, "published": "2022-09-06T18:15:15.200", "references": [{"source": "security@wordfence.com", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/168479/WordPress-WP-UserOnline-2.88.0-Cross-Site-Scripting.html"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://plugins.trac.wordpress.org/changeset?sfp_email=&sfph_mail=&reponame=&old=2770235%40wp-useronline&new=2770235%40wp-useronline&sfp_email=&sfph_mail="}, {"source": "security@wordfence.com", "tags": ["Third Party Advisory"], "url": "https://www.wordfence.com/vulnerability-advisories/#CVE-2022-2941"}], "sourceIdentifier": "security@wordfence.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@wordfence.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, "type": "CWE-79"}
| 309
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# WP-UserOnline\nContributors: GamerZ \nDonate link: https://lesterchan.net/site/donation/ \nTags: useronline, usersonline, wp-useronline, online, users, user, ajax, widget \nRequires at least: 4.0 \nTested up to: 6.0 ",
"Stable tag: 2.88.1 ",
"License: GPLv2 or later \nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html ",
"Enable you to display how many users are online on your Wordpress blog with detailed statistics.",
"## Description\nThis plugin enables you to display how many users are online on your Wordpress site, with detailed statistics of where they are and who they are (Members/Guests/Search Bots).",
"### Usage (With Widget)\n1. Go to `WP-Admin -> Appearance -> Widgets`\n1. The widget name is <strong>UserOnline</strong>.\n1. Scroll down for instructions on how to create a *UserOnline Page*.",
"### Usage (Without Widget)\n* Open `wp-content/themes/<YOUR THEME NAME>/sidebar.php` and add Anywhere:",
"```php\n<?php if (function_exists('users_online')): ?>\n\t<p>Users online: <div id=\"useronline-count\"><?php users_online(); ?></div></p>\n<?php endif; ?>\n```",
"### Build Status\n[](https://travis-ci.org/lesterchan/wp-useronline)",
"### Development\n[https://github.com/lesterchan/wp-useronline](https://github.com/lesterchan/wp-useronline \"https://github.com/lesterchan/wp-useronline\")",
"### Credits\n* Plugin icon by [Freepik](http://www.freepik.com) from [Flaticon](http://www.flaticon.com)",
"### Donations\nI spent most of my free time creating, updating, maintaining and supporting these plugins, if you really love my plugins and could spare me a couple of bucks, I will really appreciate it. If not feel free to use it without any obligations.",
"## Screenshots",
"1. Admin - Dashboard's Right Now\n2. UserOnline Page\n3. Admin - Settings Page",
"## Frequently Asked Questions",
"### Creating A UserOnline Page\n1. Go to `WP-Admin -> Pages -> Add New`\n1. Type any title you like in the post's title area\n1. If you ARE using nice permalinks, after typing the title, WordPress will generate the permalink to the page. You will see an 'Edit' link just beside the permalink.\n1. Click 'Edit' and type in `useronline` in the text field and click 'Save'.\n1. Type `[page_useronline]` in the post's content area\n1. Click 'Publish'",
"If you ARE NOT using nice permalinks, you need to go to `WP-Admin -> Settings -> UserOnline` and under 'UserOnline URL', you need to fill in the URL to the UserOnline Page you created above.",
"### To Display Most Number Of Users Online\n* Use:\n```php\n<?php if (function_exists('get_most_users_online')): ?>\n <p>Most Users Ever Online Is <?php echo get_most_users_online(); ?> On <?php echo get_most_users_online_date(); ?></p>\n<?php endif; ?>\n```",
"### To Display Users Browsing Site\n* Use:\n```php\n<?php if (function_exists('get_users_browsing_site')): ?>\n <div id=\"useronline-browsing-site\"><?php echo get_users_browsing_site(); ?></div>\n<?php endif; ?>\n```",
"### To Display Users Browsing A Page\n* Use:\n```php\n<?php if (function_exists('get_users_browsing_page')): ?>\n <div id=\"useronline-browsing-page\"><?php echo get_users_browsing_page(); ?></div>\n<?php endif; ?>\n```",
"### Error on activation: \"Parse error: syntax error, unexpected...\"",
"Make sure your host is running PHP 5. The only foolproof way to do this is to add this line to wp-config.php (after the opening `<?php` tag):",
"`var_dump(PHP_VERSION);`",
"## Changelog",
"### 2.88.1\n* FIXED: Fixed XSS. Props Juampa Rodriguez.\n",
"### 2.88.0\n* NEW: Bump to WordPress 6.0.\n* FIXED: Fixed XSS. Props @steffinstanly.",
"### 2.85.6\n* NEW: Bump to WordPress 5.6\n* NEW: Added more bots\n* NEW: Remove hardcoded Archive text in page title\n* FIXED: Update SCB Framework to support PHP 8",
"### 2.85.5\n* NEW: Bump to WordPress 5.4\n* NEW: Added more bots",
"### 2.87.4\n* NEW: Bump to WordPress 5.3\n* NEW: Added more bots\n* FIXED: Update SCB Framework To Remove contextual_help",
"### 2.87.3\n* FIXED: Duplicated Settings Saved admin_notices\n* FIXED: Missing arrow\n* FIXED: Updated bots list",
"### 2.87.2\n* NEW: Bump to 4.9\n* FIXED: Notices in SCB Framework",
"### 2.87.1\n* NEW: Bump to 4.7\n* NEW: New useronline_custom_template filter",
"### 2.87\n* NEW: Remove po/mo files from the plugin\n* NEW: Use translate.wordpress.org to translate the plugin\n* FIXED: Update SCB Framework\n* FIXED: Incompatible scbAdminPage::validate()",
"### 2.86\n* FIXED: Notices in Widget Constructor for WordPress 4.3",
"### 2.85\n* NEW: Uses WordPress native uninstall.php",
"### 2.84\n* NEW: Bump to 4.0",
"### 2.83\n* Show user agent when hovering over IP, instead of address lookup\n* Use local time for UserOnline Page\n* Fixed 'Strict Standards: Non-static method' warnings\n* Update scb Framework",
"### 2.82\n* show most recent visitors first\n* fix duplicate entry errors\n* fix ajax requests for SSL",
"### 2.81\n* fixed settings page\n* fixed \"Return to default\" buttons\n* show user list in admin only to users with 'manage_options' capability\n* added 'useronline_bots' filter",
"### 2.80\n* don't show url and referral links for users in the admin area\n* smarter detection via ajax requests\n* fix SQL errors",
"### 2.72\n* fix fatal error on upgrade",
"### 2.71\n* fix %USERONLINE_COUNT% problem",
"### 2.70\n* added option to link user names to their author page\n* allow displaying online users from a different page than the current page\n* bundle language files\n* [more info](http://scribu.net/wordpress/wp-useronline/wu-2-70.html)",
"### 2.62 (2010-03-07)\n* fix integration with WP-Stats\n* fix error with get_admin_page_title()"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [90, 210, 7], "buggy_code_start_loc": [7, 68, 6], "filenames": ["README.md", "admin.php", "wp-useronline.php"], "fixing_code_end_loc": [94, 220, 7], "fixing_code_start_loc": [7, 68, 6], "message": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wp-useronline_project:wp-useronline:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "18214189-9B13-4D53-ACE3-8213B73CF4F2", "versionEndExcluding": null, "versionEndIncluding": "2.88.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled."}, {"lang": "es", "value": "El plugin WP-UserOnline para WordPress presenta m\u00faltiples vulnerabilidades de tipo Cross-Site Scripting Almacenado en versiones hasta 2.88.0 incluy\u00e9ndola. Esto es debido a que todos los campos de la secci\u00f3n \"Naming Conventions\" no sanean apropiadamente la entrada del usuario, ni la escapan en la salida. Esto hace posible a atacantes autenticados, con privilegios administrativos, inyectar c\u00f3digo JavaScript en la configuraci\u00f3n que es ejecutada cada vez que un usuario acceda a la p\u00e1gina inyectada. Esto s\u00f3lo afecta a las instalaciones multisitio y a las instalaciones en las que se ha desactivado unfiltered_html.\n"}], "evaluatorComment": null, "id": "CVE-2022-2941", "lastModified": "2022-10-01T02:16:20.627", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security@wordfence.com", "type": "Secondary"}]}, "published": "2022-09-06T18:15:15.200", "references": [{"source": "security@wordfence.com", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/168479/WordPress-WP-UserOnline-2.88.0-Cross-Site-Scripting.html"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://plugins.trac.wordpress.org/changeset?sfp_email=&sfph_mail=&reponame=&old=2770235%40wp-useronline&new=2770235%40wp-useronline&sfp_email=&sfph_mail="}, {"source": "security@wordfence.com", "tags": ["Third Party Advisory"], "url": "https://www.wordfence.com/vulnerability-advisories/#CVE-2022-2941"}], "sourceIdentifier": "security@wordfence.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@wordfence.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, "type": "CWE-79"}
| 309
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"class UserOnline_Admin_Integration extends scbAdminPage {",
"\tfunction setup() {\n\t\t$this->textdomain = 'wp-useronline';",
"\t\t$this->args = array(\n\t\t\t'page_title' => __( 'Users Online Now', $this->textdomain ),\n\t\t\t'menu_title' => __( 'WP-UserOnline', $this->textdomain ),\n\t\t\t'page_slug' => 'useronline',\n\t\t\t'parent' => 'index.php',\n\t\t\t'action_link' => false,\n\t\t\t'capability' => 'list_users',\n\t\t);",
"\t\tadd_action( 'rightnow_end', array( $this, 'rightnow' ) );\n\t}",
"\tfunction rightnow() {\n\t\tif ( !current_user_can( 'manage_options' ) )\n\t\t\treturn;",
"\t\t$total_users = get_users_online_count();",
"\t\t$str = _n(\n\t\t\t\"There is <strong><a href='%s'>%s user</a></strong> online now.\",\n\t\t\t\"There are a total of <strong><a href='%s'>%s users</a></strong> online now.\",\n\t\t\t$total_users, 'wp-useronline'\n\t\t);",
"\t\t$out = sprintf( $str, add_query_arg( 'page', $this->args['page_slug'], admin_url( 'index.php' ) ), number_format_i18n( $total_users ) );\n\t\t$out .= '<br>';",
"\t\tif ( $tmp = get_users_browsing_site() )\n\t\t\t$out .= $tmp . '<br>';",
"\t\t$out .= UserOnline_Template::format_most_users();",
"\t\techo html( 'p', $out );\n\t}",
"\tfunction page_content() {\n\t\techo users_online_page();\n\t}\n}",
"\nclass UserOnline_Options extends scbAdminPage {",
"\tpublic function setup() {\n\t\t$this->textdomain = 'wp-useronline';",
"\t\t$this->args = array(\n\t\t\t'page_title' => __( 'UserOnline Options', $this->textdomain ),\n\t\t\t'menu_title' => __( 'UserOnline', $this->textdomain ),\n\t\t\t'page_slug' => 'useronline-settings',\n\t\t);",
"\t\t$this->option_name = 'useronline';\n\t}",
"\tpublic function validate( $options, $old_data = array() ) {\n\t\t$options['timeout'] = isset( $options['timeout'] ) ? absint( $options['timeout'] ) : 0;\n\t\t$options['url'] = ! empty( $options['url'] ) ? esc_url_raw( trim( $options['url'] ) ) : '';\n\t\t$options['names'] = ! empty( $options['names'] ) ? (int) $options['names'] : 0;\n",
"\t\tforeach ( $options['templates'] as $key => $template )\n\t\t\tif ( is_array( $template ) )",
"\t\t\t\t$options['templates'][$key]['text'] = wp_kses_post( trim( $template['text'] ) );",
"\t\t\telse",
"\t\t\t\t$options['templates'][$key] = wp_kses_post( trim( $template ) );",
"",
"\n\t\treturn $options;\n\t}",
"\tpublic function page_head() {\n?>\n<style type=\"text/css\">\n.form-table td {vertical-align: top}\n.form-table .form-table {margin-top: 0}\n.form-table .form-table th, .form-table .form-table td {padding: 0}\n.form-table textarea {width: 100%; height: 150px}\n</style>",
"<script type=\"text/javascript\">\n\tfunction useronline_default_naming() {\n\t\tjQuery( \"#current_naming\" ).html( jQuery( \"#default_naming\" ).html() );",
"\t\treturn false;\n\t}",
"\tfunction useronline_default_template( template ) {\n\t\tjQuery( '#current_template_' + template ).html( jQuery( '#default_template_' + template ).html() );",
"\t\treturn false;\n\t}\n</script>\n<?php\n\t}",
"\tpublic function page_content() {\n\t\t$options = $this->options->get();\n\t\t$defaults = $this->options->get_defaults();",
"?>\n\t<form method=\"post\" action=\"\">\n\t\t<?php wp_nonce_field( $this->nonce ); ?>\n\t\t<table class=\"form-table\">\n<?php\n\t\t$rows = array(\n\t\t\tarray(\n\t\t\t\t'title' => __( 'Time Out', 'wp-useronline' ),\n\t\t\t\t'type' => 'text',\n\t\t\t\t'name' => 'timeout',\n\t\t\t\t'desc' => '<br />' . __( 'How long until it will remove the user from the database (in seconds).', 'wp-useronline' ),\n\t\t\t\t'extra' => 'size=\"4\"'\n\t\t\t),",
"\t\t\tarray(\n\t\t\t\t'title' => __( 'UserOnline URL', 'wp-useronline' ),\n\t\t\t\t'type' => 'text',\n\t\t\t\t'name' => 'url',\n\t\t\t\t'desc' => '<br />' . __( 'URL To UserOnline Page<br />Example: http://www.yoursite.com/useronline/<br />Example: http://www.yoursite.com/?page_id=2', 'wp-useronline' ),\n\t\t\t),",
"\t\t\tarray(\n\t\t\t\t'title' => __( 'Link user names?', 'wp-useronline' ),\n\t\t\t\t'type' => 'radio',\n\t\t\t\t'name' => 'names',\n\t\t\t\t'choices' => array( 1 => __( 'Yes', 'wp-useronline' ), 0 => __( 'No', 'wp-useronline' ) ),\n\t\t\t\t'desc' => '<br />' . __( 'Link user names to their author page', 'wp-useronline' )\n\t\t\t),\n\t\t);",
"\t\tforeach ( $rows as $row ) {\n\t\t\techo $this->table_row( $row );\n\t\t}",
"?>\n\t\t<tbody id=\"default_naming\" style=\"display:none\">\n\t\t\t<?php $this->naming_table( $defaults ); ?>\n\t\t</tbody>",
"\t\t<tbody id=\"current_naming\">\n\t\t\t<?php $this->naming_table( $options ); ?>\n\t\t</tbody>",
"\t\t</table>",
"\t\t<h3><?php _e( 'Useronline Templates', 'wp-useronline' ); ?></h3>\n\t\t<table class=\"form-table\">\n\t\t\t<tbody id=\"default_template_useronline\" style=\"display:none\">\n\t\t\t\t<?php $this->useronline_template_table( $defaults ); ?>\n\t\t\t</tbody>",
"\t\t\t<tbody id=\"current_template_useronline\">\n\t\t\t\t<?php $this->useronline_template_table( $options ); ?>\n\t\t\t</tbody>",
"\t\t\t<?php\n\t\t\t$templates = array(\n\t\t\t\t'browsingsite' => __( 'User(s) Browsing Site:', 'wp-useronline' ),\n\t\t\t\t'browsingpage' => __( 'User(s) Browsing Page:', 'wp-useronline' ),\n\t\t\t);\n\t\t\tforeach ( $templates as $name => $title ) { ?>\n\t\t\t\t<tbody id=\"default_template_<?php echo $name; ?>\" style=\"display:none\">\n\t\t\t\t\t<?php $this->template_table( $title, $name, $defaults ); ?>\n\t\t\t\t</tbody>",
"\t\t\t\t<tbody id=\"current_template_<?php echo $name; ?>\">\n\t\t\t\t\t<?php $this->template_table( $title, $name, $options ); ?>\n\t\t\t\t</tbody>\n\t\t\t<?php } ?>\n\t\t</table>\n\t\t<p class=\"submit\">\n\t\t\t<input type=\"submit\" name=\"action\" class=\"button\" value=\"<?php _e( 'Save Changes', 'wp-useronline' ); ?>\" />\n\t\t</p>\n\t</form>\n<?php\n\t}",
"\tprivate function naming_table( $data ) {\n?>\n\t\t\t<tr>\n\t\t\t\t<td width=\"30%\">\n\t\t\t\t\t<strong><?php _e( 'Naming Conventions:', 'wp-useronline' ); ?></strong><br /><br />\n\t\t\t\t\t<?php _e( 'Allowed Variables:', 'wp-useronline' ); ?><br />\n\t\t\t\t\t- %COUNT%<br /><br />\n\t\t\t\t\t<input type=\"button\" value=\"<?php _e( 'Restore Defaults', 'wp-useronline' ); ?>\" onclick=\"useronline_default_naming();\" class=\"button\" />\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<table class=\"form-table\">\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Singular Form', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Plural Form', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tforeach ( array( 'user', 'member', 'guest', 'bot' ) as $tmp ) {\n\t\t\t\t\t\t\t\techo \"\\n<tr>\\n\";\n\t\t\t\t\t\t\t\tforeach ( array( $tmp, $tmp . 's' ) as $type ) {\n\t\t\t\t\t\t\t\t\techo $this->input( array(\n\t\t\t\t\t\t\t\t\t\t'type' => 'text',\n\t\t\t\t\t\t\t\t\t\t'name' => array( 'naming', $type ),\n\t\t\t\t\t\t\t\t\t\t'extra' => 'size=\"30\"',",
"\t\t\t\t\t\t\t\t\t\t'desc' => html( 'td', '%input%' )",
"\t\t\t\t\t\t\t\t\t), $data );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\techo \"\\n</tr>\\n\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t</tbody>\n\t\t\t\t\t</table>\n\t\t\t\t\t<br />\n\t\t\t\t</td>\n\t\t\t</tr>\n<?php\n\t}",
"\tprivate function useronline_template_table( $data ) {\n?>\n\t\t\t<tr>\n\t\t\t\t<td width=\"30%\">\n\t\t\t\t\t<strong><?php _e( 'User(s) Online:', 'wp-useronline' ); ?></strong><br /><br />\n\t\t\t\t\t<?php _e( 'Allowed Variables:', 'wp-useronline' ); ?><br />\n\t\t\t\t\t- %USERS%<br />\n\t\t\t\t\t- %PAGE_URL%<br />\n\t\t\t\t\t- %MOSTONLINE_COUNT%<br />\n\t\t\t\t\t- %MOSTONLINE_DATE%<br /><br />\n\t\t\t\t\t<input type=\"button\" value=\"<?php _e( 'Restore Default Template', 'wp-useronline' ); ?>\" onclick=\"useronline_default_template( 'useronline' );\" class=\"button\" />\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<?php echo $this->input( array(\n\t\t\t\t\t\t'type' => 'textarea',\n\t\t\t\t\t\t'name' => array( 'templates', 'useronline' ),\n\t\t\t\t\t), $data ); ?>\n\t\t\t\t</td>\n\t\t\t</tr>\n<?php\n\t}",
"\tprivate function template_table( $title, $option, $data ) {\n?>\n\t\t\t<tr>\n\t\t\t\t<td width=\"30%\">\n\t\t\t\t\t<strong><?php echo $title; ?></strong><br /><br />\n\t\t\t\t\t<?php _e( 'Allowed Variables:', 'wp-useronline' ); ?><br />\n\t\t\t\t\t- %USERS%<br />\n\t\t\t\t\t- %MEMBERS%<br />\n\t\t\t\t\t- %MEMBER_NAMES%<br />\n\t\t\t\t\t- %GUESTS_SEPARATOR%<br />\n\t\t\t\t\t- %GUESTS%<br />\n\t\t\t\t\t- %BOTS_SEPARATOR%<br />\n\t\t\t\t\t- %BOTS%<br /><br />\n\t\t\t\t\t<input type=\"button\" value=\"<?php _e( 'Restore Default Template', 'wp-useronline' ); ?>\" onclick=\"useronline_default_template( '<?php echo $option; ?>' );\" class=\"button\" />\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<table class=\"form-table\">\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Member Names Separator', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Guests Separator', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Bots Separator', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<?php foreach ( array_keys( $this->options->templates[$option]['separators'] ) as $type ) {\n\t\t\t\t\t\t\t\techo html( 'td', $this->input( array(\n\t\t\t\t\t\t\t\t\t'type' => 'text',\n\t\t\t\t\t\t\t\t\t'name' => array( 'templates', $option, 'separators', $type ),\n\t\t\t\t\t\t\t\t\t'extra' => \"size='15'\",\n\t\t\t\t\t\t\t\t), $data ) );\n\t\t\t\t\t\t\t} ?>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t<br />\n\t\t\t\t\t<?php echo $this->input( array(\n\t\t\t\t\t\t'type' => 'textarea',\n\t\t\t\t\t\t'name' => array( 'templates', $option, 'text' )\n\t\t\t\t\t), $data ); ?>\n\t\t\t\t</td>\n\t\t\t</tr>\n<?php\n\t}\n}"
] |
[
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,
1,
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": [90, 210, 7], "buggy_code_start_loc": [7, 68, 6], "filenames": ["README.md", "admin.php", "wp-useronline.php"], "fixing_code_end_loc": [94, 220, 7], "fixing_code_start_loc": [7, 68, 6], "message": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wp-useronline_project:wp-useronline:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "18214189-9B13-4D53-ACE3-8213B73CF4F2", "versionEndExcluding": null, "versionEndIncluding": "2.88.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled."}, {"lang": "es", "value": "El plugin WP-UserOnline para WordPress presenta m\u00faltiples vulnerabilidades de tipo Cross-Site Scripting Almacenado en versiones hasta 2.88.0 incluy\u00e9ndola. Esto es debido a que todos los campos de la secci\u00f3n \"Naming Conventions\" no sanean apropiadamente la entrada del usuario, ni la escapan en la salida. Esto hace posible a atacantes autenticados, con privilegios administrativos, inyectar c\u00f3digo JavaScript en la configuraci\u00f3n que es ejecutada cada vez que un usuario acceda a la p\u00e1gina inyectada. Esto s\u00f3lo afecta a las instalaciones multisitio y a las instalaciones en las que se ha desactivado unfiltered_html.\n"}], "evaluatorComment": null, "id": "CVE-2022-2941", "lastModified": "2022-10-01T02:16:20.627", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security@wordfence.com", "type": "Secondary"}]}, "published": "2022-09-06T18:15:15.200", "references": [{"source": "security@wordfence.com", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/168479/WordPress-WP-UserOnline-2.88.0-Cross-Site-Scripting.html"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://plugins.trac.wordpress.org/changeset?sfp_email=&sfph_mail=&reponame=&old=2770235%40wp-useronline&new=2770235%40wp-useronline&sfp_email=&sfph_mail="}, {"source": "security@wordfence.com", "tags": ["Third Party Advisory"], "url": "https://www.wordfence.com/vulnerability-advisories/#CVE-2022-2941"}], "sourceIdentifier": "security@wordfence.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@wordfence.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, "type": "CWE-79"}
| 309
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"class UserOnline_Admin_Integration extends scbAdminPage {",
"\tfunction setup() {\n\t\t$this->textdomain = 'wp-useronline';",
"\t\t$this->args = array(\n\t\t\t'page_title' => __( 'Users Online Now', $this->textdomain ),\n\t\t\t'menu_title' => __( 'WP-UserOnline', $this->textdomain ),\n\t\t\t'page_slug' => 'useronline',\n\t\t\t'parent' => 'index.php',\n\t\t\t'action_link' => false,\n\t\t\t'capability' => 'list_users',\n\t\t);",
"\t\tadd_action( 'rightnow_end', array( $this, 'rightnow' ) );\n\t}",
"\tfunction rightnow() {\n\t\tif ( !current_user_can( 'manage_options' ) )\n\t\t\treturn;",
"\t\t$total_users = get_users_online_count();",
"\t\t$str = _n(\n\t\t\t\"There is <strong><a href='%s'>%s user</a></strong> online now.\",\n\t\t\t\"There are a total of <strong><a href='%s'>%s users</a></strong> online now.\",\n\t\t\t$total_users, 'wp-useronline'\n\t\t);",
"\t\t$out = sprintf( $str, add_query_arg( 'page', $this->args['page_slug'], admin_url( 'index.php' ) ), number_format_i18n( $total_users ) );\n\t\t$out .= '<br>';",
"\t\tif ( $tmp = get_users_browsing_site() )\n\t\t\t$out .= $tmp . '<br>';",
"\t\t$out .= UserOnline_Template::format_most_users();",
"\t\techo html( 'p', $out );\n\t}",
"\tfunction page_content() {\n\t\techo users_online_page();\n\t}\n}",
"\nclass UserOnline_Options extends scbAdminPage {",
"\tpublic function setup() {\n\t\t$this->textdomain = 'wp-useronline';",
"\t\t$this->args = array(\n\t\t\t'page_title' => __( 'UserOnline Options', $this->textdomain ),\n\t\t\t'menu_title' => __( 'UserOnline', $this->textdomain ),\n\t\t\t'page_slug' => 'useronline-settings',\n\t\t);",
"\t\t$this->option_name = 'useronline';\n\t}",
"\tpublic function validate( $options, $old_data = array() ) {\n\t\t$options['timeout'] = isset( $options['timeout'] ) ? absint( $options['timeout'] ) : 0;\n\t\t$options['url'] = ! empty( $options['url'] ) ? esc_url_raw( trim( $options['url'] ) ) : '';\n\t\t$options['names'] = ! empty( $options['names'] ) ? (int) $options['names'] : 0;\n",
"\t\tforeach ( $options['naming'] as $key => $template ) {\n\t\t\t$options['naming'][$key] = wp_kses_post( trim( $template ) );\n\t\t}\n\t\tforeach ( $options['templates'] as $key => $template ) {\n\t\t\tif ( is_array( $template ) ) {",
"\t\t\t\t$options['templates'][$key]['text'] = wp_kses_post( trim( $template['text'] ) );",
"\t\t\t\tif ( ! empty( $template['separators'] ) && is_array( $template['separators'] ) ) {\n\t\t\t\t\t\tforeach( $template['separators'] as $seperator_key => $seperator_value ) {\n\t\t\t\t\t\t\t$options['templates'][$key]['separators'][$seperator_key] = wp_kses_post( trim( $seperator_value ) );\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {",
"\t\t\t\t$options['templates'][$key] = wp_kses_post( trim( $template ) );",
"\t\t\t}\n\t\t}",
"\n\t\treturn $options;\n\t}",
"\tpublic function page_head() {\n?>\n<style type=\"text/css\">\n.form-table td {vertical-align: top}\n.form-table .form-table {margin-top: 0}\n.form-table .form-table th, .form-table .form-table td {padding: 0}\n.form-table textarea {width: 100%; height: 150px}\n</style>",
"<script type=\"text/javascript\">\n\tfunction useronline_default_naming() {\n\t\tjQuery( \"#current_naming\" ).html( jQuery( \"#default_naming\" ).html() );",
"\t\treturn false;\n\t}",
"\tfunction useronline_default_template( template ) {\n\t\tjQuery( '#current_template_' + template ).html( jQuery( '#default_template_' + template ).html() );",
"\t\treturn false;\n\t}\n</script>\n<?php\n\t}",
"\tpublic function page_content() {\n\t\t$options = $this->options->get();\n\t\t$defaults = $this->options->get_defaults();",
"?>\n\t<form method=\"post\" action=\"\">\n\t\t<?php wp_nonce_field( $this->nonce ); ?>\n\t\t<table class=\"form-table\">\n<?php\n\t\t$rows = array(\n\t\t\tarray(\n\t\t\t\t'title' => __( 'Time Out', 'wp-useronline' ),\n\t\t\t\t'type' => 'text',\n\t\t\t\t'name' => 'timeout',\n\t\t\t\t'desc' => '<br />' . __( 'How long until it will remove the user from the database (in seconds).', 'wp-useronline' ),\n\t\t\t\t'extra' => 'size=\"4\"'\n\t\t\t),",
"\t\t\tarray(\n\t\t\t\t'title' => __( 'UserOnline URL', 'wp-useronline' ),\n\t\t\t\t'type' => 'text',\n\t\t\t\t'name' => 'url',\n\t\t\t\t'desc' => '<br />' . __( 'URL To UserOnline Page<br />Example: http://www.yoursite.com/useronline/<br />Example: http://www.yoursite.com/?page_id=2', 'wp-useronline' ),\n\t\t\t),",
"\t\t\tarray(\n\t\t\t\t'title' => __( 'Link user names?', 'wp-useronline' ),\n\t\t\t\t'type' => 'radio',\n\t\t\t\t'name' => 'names',\n\t\t\t\t'choices' => array( 1 => __( 'Yes', 'wp-useronline' ), 0 => __( 'No', 'wp-useronline' ) ),\n\t\t\t\t'desc' => '<br />' . __( 'Link user names to their author page', 'wp-useronline' )\n\t\t\t),\n\t\t);",
"\t\tforeach ( $rows as $row ) {\n\t\t\techo $this->table_row( $row );\n\t\t}",
"?>\n\t\t<tbody id=\"default_naming\" style=\"display:none\">\n\t\t\t<?php $this->naming_table( $defaults ); ?>\n\t\t</tbody>",
"\t\t<tbody id=\"current_naming\">\n\t\t\t<?php $this->naming_table( $options ); ?>\n\t\t</tbody>",
"\t\t</table>",
"\t\t<h3><?php _e( 'Useronline Templates', 'wp-useronline' ); ?></h3>\n\t\t<table class=\"form-table\">\n\t\t\t<tbody id=\"default_template_useronline\" style=\"display:none\">\n\t\t\t\t<?php $this->useronline_template_table( $defaults ); ?>\n\t\t\t</tbody>",
"\t\t\t<tbody id=\"current_template_useronline\">\n\t\t\t\t<?php $this->useronline_template_table( $options ); ?>\n\t\t\t</tbody>",
"\t\t\t<?php\n\t\t\t$templates = array(\n\t\t\t\t'browsingsite' => __( 'User(s) Browsing Site:', 'wp-useronline' ),\n\t\t\t\t'browsingpage' => __( 'User(s) Browsing Page:', 'wp-useronline' ),\n\t\t\t);\n\t\t\tforeach ( $templates as $name => $title ) { ?>\n\t\t\t\t<tbody id=\"default_template_<?php echo $name; ?>\" style=\"display:none\">\n\t\t\t\t\t<?php $this->template_table( $title, $name, $defaults ); ?>\n\t\t\t\t</tbody>",
"\t\t\t\t<tbody id=\"current_template_<?php echo $name; ?>\">\n\t\t\t\t\t<?php $this->template_table( $title, $name, $options ); ?>\n\t\t\t\t</tbody>\n\t\t\t<?php } ?>\n\t\t</table>\n\t\t<p class=\"submit\">\n\t\t\t<input type=\"submit\" name=\"action\" class=\"button\" value=\"<?php _e( 'Save Changes', 'wp-useronline' ); ?>\" />\n\t\t</p>\n\t</form>\n<?php\n\t}",
"\tprivate function naming_table( $data ) {\n?>\n\t\t\t<tr>\n\t\t\t\t<td width=\"30%\">\n\t\t\t\t\t<strong><?php _e( 'Naming Conventions:', 'wp-useronline' ); ?></strong><br /><br />\n\t\t\t\t\t<?php _e( 'Allowed Variables:', 'wp-useronline' ); ?><br />\n\t\t\t\t\t- %COUNT%<br /><br />\n\t\t\t\t\t<input type=\"button\" value=\"<?php _e( 'Restore Defaults', 'wp-useronline' ); ?>\" onclick=\"useronline_default_naming();\" class=\"button\" />\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<table class=\"form-table\">\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Singular Form', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Plural Form', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t<?php\n\t\t\t\t\t\t\tforeach ( array( 'user', 'member', 'guest', 'bot' ) as $tmp ) {\n\t\t\t\t\t\t\t\techo \"\\n<tr>\\n\";\n\t\t\t\t\t\t\t\tforeach ( array( $tmp, $tmp . 's' ) as $type ) {\n\t\t\t\t\t\t\t\t\techo $this->input( array(\n\t\t\t\t\t\t\t\t\t\t'type' => 'text',\n\t\t\t\t\t\t\t\t\t\t'name' => array( 'naming', $type ),\n\t\t\t\t\t\t\t\t\t\t'extra' => 'size=\"30\"',",
"\t\t\t\t\t\t\t\t\t\t'desc' => html( 'td', $type )",
"\t\t\t\t\t\t\t\t\t), $data );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\techo \"\\n</tr>\\n\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t?>\n\t\t\t\t\t\t</tbody>\n\t\t\t\t\t</table>\n\t\t\t\t\t<br />\n\t\t\t\t</td>\n\t\t\t</tr>\n<?php\n\t}",
"\tprivate function useronline_template_table( $data ) {\n?>\n\t\t\t<tr>\n\t\t\t\t<td width=\"30%\">\n\t\t\t\t\t<strong><?php _e( 'User(s) Online:', 'wp-useronline' ); ?></strong><br /><br />\n\t\t\t\t\t<?php _e( 'Allowed Variables:', 'wp-useronline' ); ?><br />\n\t\t\t\t\t- %USERS%<br />\n\t\t\t\t\t- %PAGE_URL%<br />\n\t\t\t\t\t- %MOSTONLINE_COUNT%<br />\n\t\t\t\t\t- %MOSTONLINE_DATE%<br /><br />\n\t\t\t\t\t<input type=\"button\" value=\"<?php _e( 'Restore Default Template', 'wp-useronline' ); ?>\" onclick=\"useronline_default_template( 'useronline' );\" class=\"button\" />\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<?php echo $this->input( array(\n\t\t\t\t\t\t'type' => 'textarea',\n\t\t\t\t\t\t'name' => array( 'templates', 'useronline' ),\n\t\t\t\t\t), $data ); ?>\n\t\t\t\t</td>\n\t\t\t</tr>\n<?php\n\t}",
"\tprivate function template_table( $title, $option, $data ) {\n?>\n\t\t\t<tr>\n\t\t\t\t<td width=\"30%\">\n\t\t\t\t\t<strong><?php echo $title; ?></strong><br /><br />\n\t\t\t\t\t<?php _e( 'Allowed Variables:', 'wp-useronline' ); ?><br />\n\t\t\t\t\t- %USERS%<br />\n\t\t\t\t\t- %MEMBERS%<br />\n\t\t\t\t\t- %MEMBER_NAMES%<br />\n\t\t\t\t\t- %GUESTS_SEPARATOR%<br />\n\t\t\t\t\t- %GUESTS%<br />\n\t\t\t\t\t- %BOTS_SEPARATOR%<br />\n\t\t\t\t\t- %BOTS%<br /><br />\n\t\t\t\t\t<input type=\"button\" value=\"<?php _e( 'Restore Default Template', 'wp-useronline' ); ?>\" onclick=\"useronline_default_template( '<?php echo $option; ?>' );\" class=\"button\" />\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<table class=\"form-table\">\n\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Member Names Separator', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Guests Separator', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t\t<th><?php _e( 'Bots Separator', 'wp-useronline' ); ?></th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<?php foreach ( array_keys( $this->options->templates[$option]['separators'] ) as $type ) {\n\t\t\t\t\t\t\t\techo html( 'td', $this->input( array(\n\t\t\t\t\t\t\t\t\t'type' => 'text',\n\t\t\t\t\t\t\t\t\t'name' => array( 'templates', $option, 'separators', $type ),\n\t\t\t\t\t\t\t\t\t'extra' => \"size='15'\",\n\t\t\t\t\t\t\t\t), $data ) );\n\t\t\t\t\t\t\t} ?>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t<br />\n\t\t\t\t\t<?php echo $this->input( array(\n\t\t\t\t\t\t'type' => 'textarea',\n\t\t\t\t\t\t'name' => array( 'templates', $option, 'text' )\n\t\t\t\t\t), $data ); ?>\n\t\t\t\t</td>\n\t\t\t</tr>\n<?php\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [90, 210, 7], "buggy_code_start_loc": [7, 68, 6], "filenames": ["README.md", "admin.php", "wp-useronline.php"], "fixing_code_end_loc": [94, 220, 7], "fixing_code_start_loc": [7, 68, 6], "message": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wp-useronline_project:wp-useronline:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "18214189-9B13-4D53-ACE3-8213B73CF4F2", "versionEndExcluding": null, "versionEndIncluding": "2.88.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled."}, {"lang": "es", "value": "El plugin WP-UserOnline para WordPress presenta m\u00faltiples vulnerabilidades de tipo Cross-Site Scripting Almacenado en versiones hasta 2.88.0 incluy\u00e9ndola. Esto es debido a que todos los campos de la secci\u00f3n \"Naming Conventions\" no sanean apropiadamente la entrada del usuario, ni la escapan en la salida. Esto hace posible a atacantes autenticados, con privilegios administrativos, inyectar c\u00f3digo JavaScript en la configuraci\u00f3n que es ejecutada cada vez que un usuario acceda a la p\u00e1gina inyectada. Esto s\u00f3lo afecta a las instalaciones multisitio y a las instalaciones en las que se ha desactivado unfiltered_html.\n"}], "evaluatorComment": null, "id": "CVE-2022-2941", "lastModified": "2022-10-01T02:16:20.627", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security@wordfence.com", "type": "Secondary"}]}, "published": "2022-09-06T18:15:15.200", "references": [{"source": "security@wordfence.com", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/168479/WordPress-WP-UserOnline-2.88.0-Cross-Site-Scripting.html"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://plugins.trac.wordpress.org/changeset?sfp_email=&sfph_mail=&reponame=&old=2770235%40wp-useronline&new=2770235%40wp-useronline&sfp_email=&sfph_mail="}, {"source": "security@wordfence.com", "tags": ["Third Party Advisory"], "url": "https://www.wordfence.com/vulnerability-advisories/#CVE-2022-2941"}], "sourceIdentifier": "security@wordfence.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@wordfence.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, "type": "CWE-79"}
| 309
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*\nPlugin Name: WP-UserOnline\nPlugin URI: https://lesterchan.net/portfolio/programming/php/\nDescription: Enable you to display how many users are online on your Wordpress site",
"Version: 2.88.0",
"Author: Lester 'GaMerZ' Chan\nAuthor URI: https://lesterchan.net\nText Domain: wp-useronline\n*/",
"if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly",
"include __DIR__ . '/scb/load.php';",
"function _useronline_init() {\n\tload_plugin_textdomain( 'wp-useronline', false, dirname( plugin_basename( __FILE__ ) ) );",
"\trequire_once __DIR__ . '/core.php';\n\trequire_once __DIR__ . '/template-tags.php';\n\trequire_once __DIR__ . '/deprecated.php';\n\trequire_once __DIR__ . '/widget.php';",
"\tnew scbTable( 'useronline', __FILE__, \"\n\t\ttimestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\tuser_type varchar( 20 ) NOT NULL default 'guest',\n\t\tuser_id bigint( 20 ) NOT NULL default 0,\n\t\tuser_name varchar( 250 ) NOT NULL default '',\n\t\tuser_ip varchar( 39 ) NOT NULL default '',\n\t\tuser_agent text NOT NULL,\n\t\tpage_title text NOT NULL,\n\t\tpage_url varchar( 255 ) NOT NULL default '',\n\t\treferral varchar( 255 ) NOT NULL default '',\n\t\tUNIQUE KEY useronline_id ( timestamp, user_type, user_ip )\n\t\", 'delete_first' );",
"\t$most = new scbOptions( 'useronline_most', __FILE__, array(\n\t\t'count' => 1,\n\t\t'date' => current_time( 'timestamp' )\n\t) );",
"\t$options = new scbOptions( 'useronline', __FILE__, array(\n\t\t'timeout' => 300,\n\t\t'url' => trailingslashit( get_bloginfo( 'url' ) ) . 'useronline',\n\t\t'names' => false,",
"\t\t'naming' => array(\n\t\t\t'user'\t\t=> __( '1 User', 'wp-useronline' ),\n\t\t\t'users'\t\t=> __( '%COUNT% Users', 'wp-useronline' ),\n\t\t\t'member'\t=> __( '1 Member', 'wp-useronline' ),\n\t\t\t'members'\t=> __( '%COUNT% Members', 'wp-useronline' ),\n\t\t\t'guest' \t=> __( '1 Guest', 'wp-useronline' ),\n\t\t\t'guests'\t=> __( '%COUNT% Guests', 'wp-useronline' ),\n\t\t\t'bot'\t\t=> __( '1 Bot', 'wp-useronline' ),\n\t\t\t'bots'\t\t=> __( '%COUNT% Bots', 'wp-useronline' )\n\t\t),",
"\t\t'templates' => array(\n\t\t\t'useronline' => '<a href=\"%PAGE_URL%\"><strong>%USERS%</strong> '.__( 'Online', 'wp-useronline' ).'</a>',",
"\t\t\t'browsingsite' => array(\n\t\t\t\t'separators' => array(\n\t\t\t\t\t'members' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'guests' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'bots' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t),\n\t\t\t\t'text' => _x( 'Users', 'Template Element', 'wp-useronline' ).': <strong>%MEMBER_NAMES%%GUESTS_SEPARATOR%%GUESTS%%BOTS_SEPARATOR%%BOTS%</strong>'\n\t\t\t),",
"\t\t\t'browsingpage' => array(\n\t\t\t\t'separators' => array(\n\t\t\t\t\t'members' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'guests' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'bots' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t),\n\t\t\t\t'text' => '<strong>%USERS%</strong> '.__( 'Browsing This Page.', 'wp-useronline' ).'<br />'._x( 'Users', 'Template Element', 'wp-useronline' ).': <strong>%MEMBER_NAMES%%GUESTS_SEPARATOR%%GUESTS%%BOTS_SEPARATOR%%BOTS%</strong>'\n\t\t\t)\n\t\t)\n\t) );",
"\tUserOnline_Core::init( $options, $most );",
"\tscbWidget::init( 'UserOnline_Widget', __FILE__, 'useronline' );",
"\tif ( is_admin() ) {\n\t\trequire_once __DIR__ . '/admin.php';\n\t\tscbAdminPage::register( 'UserOnline_Admin_Integration', __FILE__ );\n\t\tscbAdminPage::register( 'UserOnline_Options', __FILE__, UserOnline_Core::$options );\n\t}",
"\tif ( function_exists( 'stats_page' ) )\n\t\trequire_once __DIR__ . '/wp-stats.php';",
"#\tscbUtil::do_uninstall( __FILE__ );\n#\tscbUtil::do_activation( __FILE__ );\n}\nscb_init( '_useronline_init' );"
] |
[
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [90, 210, 7], "buggy_code_start_loc": [7, 68, 6], "filenames": ["README.md", "admin.php", "wp-useronline.php"], "fixing_code_end_loc": [94, 220, 7], "fixing_code_start_loc": [7, 68, 6], "message": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wp-useronline_project:wp-useronline:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "18214189-9B13-4D53-ACE3-8213B73CF4F2", "versionEndExcluding": null, "versionEndIncluding": "2.88.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled."}, {"lang": "es", "value": "El plugin WP-UserOnline para WordPress presenta m\u00faltiples vulnerabilidades de tipo Cross-Site Scripting Almacenado en versiones hasta 2.88.0 incluy\u00e9ndola. Esto es debido a que todos los campos de la secci\u00f3n \"Naming Conventions\" no sanean apropiadamente la entrada del usuario, ni la escapan en la salida. Esto hace posible a atacantes autenticados, con privilegios administrativos, inyectar c\u00f3digo JavaScript en la configuraci\u00f3n que es ejecutada cada vez que un usuario acceda a la p\u00e1gina inyectada. Esto s\u00f3lo afecta a las instalaciones multisitio y a las instalaciones en las que se ha desactivado unfiltered_html.\n"}], "evaluatorComment": null, "id": "CVE-2022-2941", "lastModified": "2022-10-01T02:16:20.627", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security@wordfence.com", "type": "Secondary"}]}, "published": "2022-09-06T18:15:15.200", "references": [{"source": "security@wordfence.com", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/168479/WordPress-WP-UserOnline-2.88.0-Cross-Site-Scripting.html"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://plugins.trac.wordpress.org/changeset?sfp_email=&sfph_mail=&reponame=&old=2770235%40wp-useronline&new=2770235%40wp-useronline&sfp_email=&sfph_mail="}, {"source": "security@wordfence.com", "tags": ["Third Party Advisory"], "url": "https://www.wordfence.com/vulnerability-advisories/#CVE-2022-2941"}], "sourceIdentifier": "security@wordfence.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@wordfence.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, "type": "CWE-79"}
| 309
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php\n/*\nPlugin Name: WP-UserOnline\nPlugin URI: https://lesterchan.net/portfolio/programming/php/\nDescription: Enable you to display how many users are online on your Wordpress site",
"Version: 2.88.1",
"Author: Lester 'GaMerZ' Chan\nAuthor URI: https://lesterchan.net\nText Domain: wp-useronline\n*/",
"if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly",
"include __DIR__ . '/scb/load.php';",
"function _useronline_init() {\n\tload_plugin_textdomain( 'wp-useronline', false, dirname( plugin_basename( __FILE__ ) ) );",
"\trequire_once __DIR__ . '/core.php';\n\trequire_once __DIR__ . '/template-tags.php';\n\trequire_once __DIR__ . '/deprecated.php';\n\trequire_once __DIR__ . '/widget.php';",
"\tnew scbTable( 'useronline', __FILE__, \"\n\t\ttimestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\tuser_type varchar( 20 ) NOT NULL default 'guest',\n\t\tuser_id bigint( 20 ) NOT NULL default 0,\n\t\tuser_name varchar( 250 ) NOT NULL default '',\n\t\tuser_ip varchar( 39 ) NOT NULL default '',\n\t\tuser_agent text NOT NULL,\n\t\tpage_title text NOT NULL,\n\t\tpage_url varchar( 255 ) NOT NULL default '',\n\t\treferral varchar( 255 ) NOT NULL default '',\n\t\tUNIQUE KEY useronline_id ( timestamp, user_type, user_ip )\n\t\", 'delete_first' );",
"\t$most = new scbOptions( 'useronline_most', __FILE__, array(\n\t\t'count' => 1,\n\t\t'date' => current_time( 'timestamp' )\n\t) );",
"\t$options = new scbOptions( 'useronline', __FILE__, array(\n\t\t'timeout' => 300,\n\t\t'url' => trailingslashit( get_bloginfo( 'url' ) ) . 'useronline',\n\t\t'names' => false,",
"\t\t'naming' => array(\n\t\t\t'user'\t\t=> __( '1 User', 'wp-useronline' ),\n\t\t\t'users'\t\t=> __( '%COUNT% Users', 'wp-useronline' ),\n\t\t\t'member'\t=> __( '1 Member', 'wp-useronline' ),\n\t\t\t'members'\t=> __( '%COUNT% Members', 'wp-useronline' ),\n\t\t\t'guest' \t=> __( '1 Guest', 'wp-useronline' ),\n\t\t\t'guests'\t=> __( '%COUNT% Guests', 'wp-useronline' ),\n\t\t\t'bot'\t\t=> __( '1 Bot', 'wp-useronline' ),\n\t\t\t'bots'\t\t=> __( '%COUNT% Bots', 'wp-useronline' )\n\t\t),",
"\t\t'templates' => array(\n\t\t\t'useronline' => '<a href=\"%PAGE_URL%\"><strong>%USERS%</strong> '.__( 'Online', 'wp-useronline' ).'</a>',",
"\t\t\t'browsingsite' => array(\n\t\t\t\t'separators' => array(\n\t\t\t\t\t'members' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'guests' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'bots' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t),\n\t\t\t\t'text' => _x( 'Users', 'Template Element', 'wp-useronline' ).': <strong>%MEMBER_NAMES%%GUESTS_SEPARATOR%%GUESTS%%BOTS_SEPARATOR%%BOTS%</strong>'\n\t\t\t),",
"\t\t\t'browsingpage' => array(\n\t\t\t\t'separators' => array(\n\t\t\t\t\t'members' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'guests' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t\t'bots' => __( ',', 'wp-useronline' ).' ',\n\t\t\t\t),\n\t\t\t\t'text' => '<strong>%USERS%</strong> '.__( 'Browsing This Page.', 'wp-useronline' ).'<br />'._x( 'Users', 'Template Element', 'wp-useronline' ).': <strong>%MEMBER_NAMES%%GUESTS_SEPARATOR%%GUESTS%%BOTS_SEPARATOR%%BOTS%</strong>'\n\t\t\t)\n\t\t)\n\t) );",
"\tUserOnline_Core::init( $options, $most );",
"\tscbWidget::init( 'UserOnline_Widget', __FILE__, 'useronline' );",
"\tif ( is_admin() ) {\n\t\trequire_once __DIR__ . '/admin.php';\n\t\tscbAdminPage::register( 'UserOnline_Admin_Integration', __FILE__ );\n\t\tscbAdminPage::register( 'UserOnline_Options', __FILE__, UserOnline_Core::$options );\n\t}",
"\tif ( function_exists( 'stats_page' ) )\n\t\trequire_once __DIR__ . '/wp-stats.php';",
"#\tscbUtil::do_uninstall( __FILE__ );\n#\tscbUtil::do_activation( __FILE__ );\n}\nscb_init( '_useronline_init' );"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [90, 210, 7], "buggy_code_start_loc": [7, 68, 6], "filenames": ["README.md", "admin.php", "wp-useronline.php"], "fixing_code_end_loc": [94, 220, 7], "fixing_code_start_loc": [7, 68, 6], "message": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:wp-useronline_project:wp-useronline:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "18214189-9B13-4D53-ACE3-8213B73CF4F2", "versionEndExcluding": null, "versionEndIncluding": "2.88.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The WP-UserOnline plugin for WordPress has multiple Stored Cross-Site Scripting vulnerabilities in versions up to, and including 2.88.0. This is due to the fact that all fields in the \"Naming Conventions\" section do not properly sanitize user input, nor escape it on output. This makes it possible for authenticated attackers, with administrative privileges, to inject JavaScript code into the setting that will execute whenever a user accesses the injected page. This only affects multi-site installations and installations where unfiltered_html has been disabled."}, {"lang": "es", "value": "El plugin WP-UserOnline para WordPress presenta m\u00faltiples vulnerabilidades de tipo Cross-Site Scripting Almacenado en versiones hasta 2.88.0 incluy\u00e9ndola. Esto es debido a que todos los campos de la secci\u00f3n \"Naming Conventions\" no sanean apropiadamente la entrada del usuario, ni la escapan en la salida. Esto hace posible a atacantes autenticados, con privilegios administrativos, inyectar c\u00f3digo JavaScript en la configuraci\u00f3n que es ejecutada cada vez que un usuario acceda a la p\u00e1gina inyectada. Esto s\u00f3lo afecta a las instalaciones multisitio y a las instalaciones en las que se ha desactivado unfiltered_html.\n"}], "evaluatorComment": null, "id": "CVE-2022-2941", "lastModified": "2022-10-01T02:16:20.627", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.7, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security@wordfence.com", "type": "Secondary"}]}, "published": "2022-09-06T18:15:15.200", "references": [{"source": "security@wordfence.com", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "http://packetstormsecurity.com/files/168479/WordPress-WP-UserOnline-2.88.0-Cross-Site-Scripting.html"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, {"source": "security@wordfence.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://plugins.trac.wordpress.org/changeset?sfp_email=&sfph_mail=&reponame=&old=2770235%40wp-useronline&new=2770235%40wp-useronline&sfp_email=&sfph_mail="}, {"source": "security@wordfence.com", "tags": ["Third Party Advisory"], "url": "https://www.wordfence.com/vulnerability-advisories/#CVE-2022-2941"}], "sourceIdentifier": "security@wordfence.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@wordfence.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/lesterchan/wp-useronline/commit/59c76b20e4e27489f93dee4ef1254d6204e08b3c"}, "type": "CWE-79"}
| 309
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% PPPP SSSSS DDDD %\n% P P SS D D %\n% PPPP SSS D D %\n% P SS D D %\n% P SSSSS DDDD %\n% %\n% %\n% Read/Write Adobe Photoshop Image Format %\n% %\n% Software Design %\n% Cristy %\n% Leonard Rosenthol %\n% July 1992 %\n% Dirk Lemstra %\n% December 2013 %\n% %\n% %\n% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% https://www.imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/channel.h\"\n#include \"MagickCore/colormap.h\"\n#include \"MagickCore/colormap-private.h\"\n#include \"MagickCore/colorspace.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/enhance.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/log.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/policy.h\"\n#include \"MagickCore/profile.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/registry.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/string-private.h\"\n#include \"MagickCore/thread-private.h\"\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n#include <zlib.h>\n#endif\n#include \"psd-private.h\"",
"/*\n Define declaractions.\n*/\n#define MaxPSDChannels 56\n#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)\n\f\n/*\n Enumerated declaractions.\n*/\ntypedef enum\n{\n Raw = 0,\n RLE = 1,\n ZipWithoutPrediction = 2,\n ZipWithPrediction = 3\n} PSDCompressionType;",
"typedef enum\n{\n BitmapMode = 0,\n GrayscaleMode = 1,\n IndexedMode = 2,\n RGBMode = 3,\n CMYKMode = 4,\n MultichannelMode = 7,\n DuotoneMode = 8,\n LabMode = 9\n} PSDImageType;\n\f\n/*\n Typedef declaractions.\n*/\ntypedef struct _ChannelInfo\n{\n short int\n type;",
" size_t\n size;\n} ChannelInfo;",
"typedef struct _MaskInfo\n{\n Image\n *image;",
" RectangleInfo\n page;",
" unsigned char\n background,\n flags;\n} MaskInfo;",
"typedef struct _LayerInfo\n{\n ChannelInfo\n channel_info[MaxPSDChannels];",
" char\n blendkey[4];",
" Image\n *image;",
" MaskInfo\n mask;",
" Quantum\n opacity;",
" RectangleInfo\n page;",
" size_t\n offset_x,\n offset_y;",
" unsigned char\n clipping,\n flags,\n name[256],\n visible;",
" unsigned short\n channels;",
" StringInfo\n *info;\n} LayerInfo;",
"/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I s P S D %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% IsPSD()() returns MagickTrue if the image format type, identified by the\n% magick string, is PSD.\n%\n% The format of the IsPSD method is:\n%\n% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n%\n% A description of each parameter follows:\n%\n% o magick: compare image format pattern against these bytes.\n%\n% o length: Specifies the length of the magick string.\n%\n*/\nstatic MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n{\n if (length < 4)\n return(MagickFalse);\n if (LocaleNCompare((const char *) magick,\"8BPS\",4) == 0)\n return(MagickTrue);\n return(MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadPSDImage() reads an Adobe Photoshop image file and returns it. It\n% allocates the memory necessary for the new Image structure and returns a\n% pointer to the new image.\n%\n% The format of the ReadPSDImage method is:\n%\n% Image *ReadPSDImage(image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/",
"static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)\n{\n const char\n *blend_mode;",
" switch (op)\n {\n case ColorBurnCompositeOp: blend_mode = \"idiv\"; break;\n case ColorDodgeCompositeOp: blend_mode = \"div \"; break;\n case ColorizeCompositeOp: blend_mode = \"colr\"; break;\n case DarkenCompositeOp: blend_mode = \"dark\"; break;\n case DifferenceCompositeOp: blend_mode = \"diff\"; break;\n case DissolveCompositeOp: blend_mode = \"diss\"; break;\n case ExclusionCompositeOp: blend_mode = \"smud\"; break;\n case HardLightCompositeOp: blend_mode = \"hLit\"; break;\n case HardMixCompositeOp: blend_mode = \"hMix\"; break;\n case HueCompositeOp: blend_mode = \"hue \"; break;\n case LightenCompositeOp: blend_mode = \"lite\"; break;\n case LinearBurnCompositeOp: blend_mode = \"lbrn\"; break;\n case LinearDodgeCompositeOp:blend_mode = \"lddg\"; break;\n case LinearLightCompositeOp:blend_mode = \"lLit\"; break;\n case LuminizeCompositeOp: blend_mode = \"lum \"; break;\n case MultiplyCompositeOp: blend_mode = \"mul \"; break;\n case OverCompositeOp: blend_mode = \"norm\"; break;\n case OverlayCompositeOp: blend_mode = \"over\"; break;\n case PinLightCompositeOp: blend_mode = \"pLit\"; break;\n case SaturateCompositeOp: blend_mode = \"sat \"; break;\n case ScreenCompositeOp: blend_mode = \"scrn\"; break;\n case SoftLightCompositeOp: blend_mode = \"sLit\"; break;\n case VividLightCompositeOp: blend_mode = \"vLit\"; break;\n default: blend_mode = \"norm\";\n }\n return(blend_mode);\n}",
"/*\n For some reason Photoshop seems to blend semi-transparent pixels with white.\n This method reverts the blending. This can be disabled by setting the\n option 'psd:alpha-unblend' to off.\n*/\nstatic MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,\n Image *image,ExceptionInfo* exception)\n{\n const char\n *option;",
" MagickBooleanType\n status;",
" ssize_t\n y;",
" if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)\n return(MagickTrue);\n option=GetImageOption(image_info,\"psd:alpha-unblend\");\n if (IsStringFalse(option) != MagickFalse)\n return(MagickTrue);\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" register ssize_t\n x;",
" if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;",
" register ssize_t\n i;",
" gamma=QuantumScale*GetPixelAlpha(image, q);\n if (gamma != 0.0 && gamma != 1.0)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n if (channel != AlphaPixelChannel)\n q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);\n }\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }",
" return(status);\n}",
"static inline CompressionType ConvertPSDCompression(\n PSDCompressionType compression)\n{\n switch (compression)\n {\n case RLE:\n return RLECompression;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n return ZipCompression;\n default:\n return NoCompression;\n }\n}",
"static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,\n MagickBooleanType revert,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" ssize_t\n y;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying layer opacity %.20g\", (double) opacity);\n if (opacity == OpaqueAlpha)\n return(MagickTrue);\n image->alpha_trait=BlendPixelTrait;\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" register ssize_t\n x;",
" if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (revert == MagickFalse)\n SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*\n opacity),q);\n else if (opacity > 0)\n SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/\n (MagickRealType) opacity)),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }",
" return(status);\n}",
"static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,\n Quantum background,MagickBooleanType revert,ExceptionInfo *exception)\n{\n Image\n *complete_mask;",
" MagickBooleanType\n status;",
" PixelInfo\n color;",
" ssize_t\n y;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying opacity mask\");\n complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,\n exception);\n complete_mask->alpha_trait=BlendPixelTrait;\n GetPixelInfo(complete_mask,&color);\n color.red=background;\n SetImageColor(complete_mask,&color,exception);\n status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,\n mask->page.x-image->page.x,mask->page.y-image->page.y,exception);\n if (status == MagickFalse)\n {\n complete_mask=DestroyImage(complete_mask);\n return(status);\n }\n image->alpha_trait=BlendPixelTrait;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" register Quantum\n *p;",
" register ssize_t\n x;",
" if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);\n if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n MagickRealType\n alpha,\n intensity;",
" alpha=GetPixelAlpha(image,q);\n intensity=GetPixelIntensity(complete_mask,p);\n if (revert == MagickFalse)\n SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);\n else if (intensity > 0)\n SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);\n q+=GetPixelChannels(image);\n p+=GetPixelChannels(complete_mask);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }\n complete_mask=DestroyImage(complete_mask);\n return(status);\n}",
"static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,\n ExceptionInfo *exception)\n{\n char\n *key;",
" RandomInfo\n *random_info;",
" StringInfo\n *key_info;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" preserving opacity mask\");\n random_info=AcquireRandomInfo();\n key_info=GetRandomKey(random_info,2+1);\n key=(char *) GetStringInfoDatum(key_info);\n key[8]=layer_info->mask.background;\n key[9]='\\0';\n layer_info->mask.image->page.x+=layer_info->page.x;\n layer_info->mask.image->page.y+=layer_info->page.y;\n (void) SetImageRegistry(ImageRegistryType,(const char *) key,\n layer_info->mask.image,exception);\n (void) SetImageArtifact(layer_info->image,\"psd:opacity-mask\",\n (const char *) key);\n key_info=DestroyStringInfo(key_info);\n random_info=DestroyRandomInfo(random_info);\n}",
"static ssize_t DecodePSDPixels(const size_t number_compact_pixels,\n const unsigned char *compact_pixels,const ssize_t depth,\n const size_t number_pixels,unsigned char *pixels)\n{\n#define CheckNumberCompactPixels \\\n if (packets == 0) \\\n return(i); \\\n packets--",
"#define CheckNumberPixels(count) \\\n if (((ssize_t) i + count) > (ssize_t) number_pixels) \\\n return(i); \\\n i+=count",
" int\n pixel;",
" register ssize_t\n i,\n j;",
" size_t\n length;",
" ssize_t\n packets;",
" packets=(ssize_t) number_compact_pixels;\n for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )\n {\n packets--;\n length=(size_t) (*compact_pixels++);\n if (length == 128)\n continue;\n if (length > 128)\n {\n length=256-length+1;\n CheckNumberCompactPixels;\n pixel=(*compact_pixels++);\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(unsigned char) ((pixel >> 6) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 4) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 2) & 0x03);\n *pixels++=(unsigned char) ((pixel & 0x03) & 0x03);\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(unsigned char) ((pixel >> 4) & 0xff);\n *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(unsigned char) pixel;\n break;\n }\n }\n }\n continue;\n }\n length++;\n for (j=0; j < (ssize_t) length; j++)\n {\n CheckNumberCompactPixels;\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(*compact_pixels >> 6) & 0x03;\n *pixels++=(*compact_pixels >> 4) & 0x03;\n *pixels++=(*compact_pixels >> 2) & 0x03;\n *pixels++=(*compact_pixels & 0x03) & 0x03;\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(*compact_pixels >> 4) & 0xff;\n *pixels++=(*compact_pixels & 0x0f) & 0xff;\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(*compact_pixels);\n break;\n }\n }\n compact_pixels++;\n }\n }\n return(i);\n}",
"static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,\n const ssize_t number_layers)\n{\n ssize_t\n i;",
" for (i=0; i<number_layers; i++)\n {\n if (layer_info[i].image != (Image *) NULL)\n layer_info[i].image=DestroyImage(layer_info[i].image);\n if (layer_info[i].mask.image != (Image *) NULL)\n layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }",
" return (LayerInfo *) RelinquishMagickMemory(layer_info);\n}",
"static inline size_t GetPSDPacketSize(Image *image)\n{\n if (image->storage_class == PseudoClass)\n {\n if (image->colors > 256)\n return(2);\n else if (image->depth > 8)\n return(2);\n }\n else\n if (image->depth > 8)\n return(2);",
" return(1);\n}",
"static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)\n{\n if (psd_info->version == 1)\n return((MagickSizeType) ReadBlobLong(image));\n return((MagickSizeType) ReadBlobLongLong(image));\n}",
"static inline size_t GetPSDRowSize(Image *image)\n{\n if (image->depth == 1)\n return(((image->columns+7)/8)*GetPSDPacketSize(image));\n else\n return(image->columns*GetPSDPacketSize(image));\n}",
"static const char *ModeToString(PSDImageType type)\n{\n switch (type)\n {\n case BitmapMode: return \"Bitmap\";\n case GrayscaleMode: return \"Grayscale\";\n case IndexedMode: return \"Indexed\";\n case RGBMode: return \"RGB\";\n case CMYKMode: return \"CMYK\";\n case MultichannelMode: return \"Multichannel\";\n case DuotoneMode: return \"Duotone\";\n case LabMode: return \"L*A*B\";\n default: return \"unknown\";\n }\n}",
"static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)\n{\n ChannelType\n channel_mask;",
" MagickBooleanType\n status;",
" channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~\n AlphaChannel));\n status=NegateImage(image,MagickFalse,exception);\n (void) SetImageChannelMask(image,channel_mask);\n return(status);\n}",
"static void ParseImageResourceBlocks(Image *image,\n const unsigned char *blocks,size_t length,\n MagickBooleanType *has_merged_image,ExceptionInfo *exception)\n{\n const unsigned char\n *p;",
" StringInfo\n *profile;",
" unsigned char\n name_length;",
" unsigned int\n count;",
" unsigned short\n id,\n short_sans;",
" if (length < 16)\n return;\n profile=BlobToStringInfo((const unsigned char *) NULL,length);\n SetStringInfoDatum(profile,blocks);\n (void) SetImageProfile(image,\"8bim\",profile,exception);\n profile=DestroyStringInfo(profile);\n for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); )\n {\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p+=4;\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushCharPixel(p,&name_length);\n if ((name_length % 2) == 0)\n name_length++;\n p+=name_length;\n if (p > (blocks+length-4))\n return;\n p=PushLongPixel(MSBEndian,p,&count);\n if ((p+count) > (blocks+length))\n return;\n switch (id)\n {\n case 0x03ed:\n {\n char\n value[MagickPathExtent];",
" unsigned short\n resolution;",
" /*\n Resolution info.\n */\n if (count < 16)\n return;\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.x=(double) resolution;\n (void) FormatLocaleString(value,MagickPathExtent,\"%g\",\n image->resolution.x);\n (void) SetImageProperty(image,\"tiff:XResolution\",value,exception);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.y=(double) resolution;\n (void) FormatLocaleString(value,MagickPathExtent,\"%g\",\n image->resolution.y);\n (void) SetImageProperty(image,\"tiff:YResolution\",value,exception);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n image->units=PixelsPerInchResolution;\n break;\n }\n case 0x0421:\n {\n if ((count > 3) && (*(p+4) == 0))\n *has_merged_image=MagickFalse;\n p+=count;\n break;\n }\n default:\n {\n p+=count;\n break;\n }\n }\n if ((count & 0x01) != 0)\n p++;\n }\n return;\n}",
"static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)\n{\n if (mode == (const char *) NULL)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"norm\",4) == 0)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"mul \",4) == 0)\n return(MultiplyCompositeOp);\n if (LocaleNCompare(mode,\"diss\",4) == 0)\n return(DissolveCompositeOp);\n if (LocaleNCompare(mode,\"diff\",4) == 0)\n return(DifferenceCompositeOp);\n if (LocaleNCompare(mode,\"dark\",4) == 0)\n return(DarkenCompositeOp);\n if (LocaleNCompare(mode,\"lite\",4) == 0)\n return(LightenCompositeOp);\n if (LocaleNCompare(mode,\"hue \",4) == 0)\n return(HueCompositeOp);\n if (LocaleNCompare(mode,\"sat \",4) == 0)\n return(SaturateCompositeOp);\n if (LocaleNCompare(mode,\"colr\",4) == 0)\n return(ColorizeCompositeOp);\n if (LocaleNCompare(mode,\"lum \",4) == 0)\n return(LuminizeCompositeOp);\n if (LocaleNCompare(mode,\"scrn\",4) == 0)\n return(ScreenCompositeOp);\n if (LocaleNCompare(mode,\"over\",4) == 0)\n return(OverlayCompositeOp);\n if (LocaleNCompare(mode,\"hLit\",4) == 0)\n return(HardLightCompositeOp);\n if (LocaleNCompare(mode,\"sLit\",4) == 0)\n return(SoftLightCompositeOp);\n if (LocaleNCompare(mode,\"smud\",4) == 0)\n return(ExclusionCompositeOp);\n if (LocaleNCompare(mode,\"div \",4) == 0)\n return(ColorDodgeCompositeOp);\n if (LocaleNCompare(mode,\"idiv\",4) == 0)\n return(ColorBurnCompositeOp);\n if (LocaleNCompare(mode,\"lbrn\",4) == 0)\n return(LinearBurnCompositeOp);\n if (LocaleNCompare(mode,\"lddg\",4) == 0)\n return(LinearDodgeCompositeOp);\n if (LocaleNCompare(mode,\"lLit\",4) == 0)\n return(LinearLightCompositeOp);\n if (LocaleNCompare(mode,\"vLit\",4) == 0)\n return(VividLightCompositeOp);\n if (LocaleNCompare(mode,\"pLit\",4) == 0)\n return(PinLightCompositeOp);\n if (LocaleNCompare(mode,\"hMix\",4) == 0)\n return(HardMixCompositeOp);\n return(OverCompositeOp);\n}",
"static inline void ReversePSDString(Image *image,char *p,size_t length)\n{\n char\n *q;",
" if (image->endian == MSBEndian)\n return;",
" q=p+length;\n for(--q; p < q; ++p, --q)\n {\n *p = *p ^ *q,\n *q = *p ^ *q,\n *p = *p ^ *q;\n }\n}",
"static inline void SetPSDPixel(Image *image,const size_t channels,\n const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,\n ExceptionInfo *exception)\n{\n if (image->storage_class == PseudoClass)\n {\n PixelInfo\n *color;",
" if (type == 0)\n {\n if (packet_size == 1)\n SetPixelIndex(image,ScaleQuantumToChar(pixel),q);\n else\n SetPixelIndex(image,ScaleQuantumToShort(pixel),q);\n }\n color=image->colormap+(ssize_t) ConstrainColormapIndex(image,\n GetPixelIndex(image,q),exception);\n if ((type == 0) && (channels > 1))\n return;\n else\n color->alpha=(MagickRealType) pixel;\n SetPixelViaPixelInfo(image,color,q);\n return;\n }\n switch (type)\n {\n case -1:\n {\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case -2:\n case 0:\n {\n SetPixelRed(image,pixel,q);\n break;\n }\n case 1:\n {\n SetPixelGreen(image,pixel,q);\n break;\n }\n case 2:\n {\n SetPixelBlue(image,pixel,q);\n break;\n }\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,pixel,q);\n else\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case 4:\n {\n if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&\n (channels > 3))\n break;\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n }\n}",
"static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const size_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;",
" register const unsigned char\n *p;",
" register Quantum\n *q;",
" register ssize_t\n x;",
" size_t\n packet_size;",
" unsigned short\n nibble;",
" p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n if (image->depth > 1)\n {\n SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);\n q+=GetPixelChannels(image);\n }\n else\n {\n ssize_t\n bit,\n number_bits;",
" number_bits=image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit = 0; bit < number_bits; bit++)\n {\n SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)\n & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);\n q+=GetPixelChannels(image);\n x++;\n }\n if (x != (ssize_t) image->columns)\n x--;\n continue;\n }\n }\n return(SyncAuthenticPixels(image,exception));\n}",
"static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,\n const ssize_t type,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" size_t\n count,\n row_size;",
" ssize_t\n y;",
" unsigned char\n *pixels;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RAW\");",
" row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);",
" status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;",
" count=ReadBlob(image,row_size,pixels);\n if (count != row_size)\n break;",
" status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);\n if (status == MagickFalse)\n break;\n }",
" pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}",
"static inline MagickOffsetType *ReadPSDRLESizes(Image *image,\n const PSDInfo *psd_info,const size_t size)\n{\n MagickOffsetType\n *sizes;",
" ssize_t\n y;",
" sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));\n if(sizes != (MagickOffsetType *) NULL)\n {\n for (y=0; y < (ssize_t) size; y++)\n {\n if (psd_info->version == 1)\n sizes[y]=(MagickOffsetType) ReadBlobShort(image);\n else\n sizes[y]=(MagickOffsetType) ReadBlobLong(image);\n }\n }\n return sizes;\n}",
"static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,\n const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" size_t\n length,\n row_size;",
" ssize_t\n count,\n y;",
" unsigned char\n *compact_pixels,\n *pixels;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RLE compressed\");",
" row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);",
" length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n if ((MagickOffsetType) length < sizes[y])\n length=(size_t) sizes[y];",
" if (length > row_size + 256) // arbitrary number\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"InvalidLength\",image->filename);\n }",
" compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }",
" (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));",
" status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;",
" count=ReadBlob(image,(size_t) sizes[y],compact_pixels);\n if (count != (ssize_t) sizes[y])\n break;",
" count=DecodePSDPixels((size_t) sizes[y],compact_pixels,\n (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);\n if (count != (ssize_t) row_size)\n break;",
" status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,\n exception);\n if (status == MagickFalse)\n break;\n }",
" compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}",
"#ifdef MAGICKCORE_ZLIB_DELEGATE\nstatic MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,\n const ssize_t type,const PSDCompressionType compression,\n const size_t compact_size,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" register unsigned char\n *p;",
" size_t\n count,\n length,\n packet_size,\n row_size;",
" ssize_t\n y;",
" unsigned char\n *compact_pixels,\n *pixels;",
" z_stream\n stream;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is ZIP compressed\");",
" compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,\n sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);",
" packet_size=GetPSDPacketSize(image);\n row_size=image->columns*packet_size;\n count=image->rows*row_size;",
" pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }",
" ResetMagickMemory(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n stream.next_in=(Bytef *)compact_pixels;\n stream.avail_in=(uInt) compact_size;\n stream.next_out=(Bytef *)pixels;\n stream.avail_out=(uInt) count;",
" if (inflateInit(&stream) == Z_OK)\n {\n int\n ret;",
" while (stream.avail_out > 0)\n {\n ret=inflate(&stream,Z_SYNC_FLUSH);\n if ((ret != Z_OK) && (ret != Z_STREAM_END))\n {\n (void) inflateEnd(&stream);\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(MagickFalse);\n }\n }\n (void) inflateEnd(&stream);\n }",
" if (compression == ZipWithPrediction)\n {\n p=pixels;\n while (count > 0)\n {\n length=image->columns;\n while (--length)\n {\n if (packet_size == 2)\n {\n p[2]+=p[0]+((p[1]+p[3]) >> 8);\n p[3]+=p[1];\n }\n else\n *(p+1)+=*p;\n p+=packet_size;\n }\n p+=packet_size;\n count-=row_size;\n }\n }",
" status=MagickTrue;\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=ReadPSDChannelPixels(image,channels,y,type,p,exception);\n if (status == MagickFalse)\n break;",
" p+=row_size;\n }",
" compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}\n#endif",
"static MagickBooleanType ReadPSDChannel(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,\n const size_t channel,const PSDCompressionType compression,\n ExceptionInfo *exception)\n{\n Image\n *channel_image,\n *mask;",
" MagickOffsetType\n offset;",
" MagickBooleanType\n status;",
" channel_image=image;\n mask=(Image *) NULL;\n if ((layer_info->channel_info[channel].type < -1) &&\n (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))\n {\n const char\n *option;",
" /*\n Ignore mask that is not a user supplied layer mask, if the mask is\n disabled or if the flags have unsupported values.\n */\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if ((layer_info->channel_info[channel].type != -2) ||\n (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&\n (IsStringTrue(option) == MagickFalse)))",
" {\n SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);\n return(MagickTrue);\n }",
" mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n if (mask != (Image *) NULL)\n {\n SetImageType(mask,GrayscaleType,exception);\n channel_image=mask;\n }\n }",
" offset=TellBlob(image);\n status=MagickFalse;\n switch(compression)\n {\n case Raw:\n status=ReadPSDChannelRaw(channel_image,psd_info->channels,\n layer_info->channel_info[channel].type,exception);\n break;\n case RLE:\n {\n MagickOffsetType\n *sizes;",
" sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n status=ReadPSDChannelRLE(channel_image,psd_info,\n layer_info->channel_info[channel].type,sizes,exception);\n sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);\n }\n break;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n status=ReadPSDChannelZip(channel_image,layer_info->channels,\n layer_info->channel_info[channel].type,compression,\n layer_info->channel_info[channel].size-2,exception);\n#else\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateWarning,\"DelegateLibrarySupportNotBuiltIn\",\n \"'%s' (ZLIB)\",image->filename);\n#endif\n break;\n default:\n (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,\n \"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n break;\n }",
" SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);\n if (status == MagickFalse)\n {\n if (mask != (Image *) NULL)\n DestroyImage(mask);\n ThrowBinaryException(CoderError,\"UnableToDecompressImage\",\n image->filename);\n }\n layer_info->mask.image=mask;\n return(status);\n}",
"static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,\n const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)\n{\n char\n message[MagickPathExtent];",
" MagickBooleanType\n status;",
" PSDCompressionType\n compression;",
" ssize_t\n j;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" setting up new layer image\");\n if (psd_info->mode != IndexedMode)\n (void) SetImageBackgroundColor(layer_info->image,exception);\n layer_info->image->compose=PSDBlendModeToCompositeOperator(\n layer_info->blendkey);\n if (layer_info->visible == MagickFalse)\n layer_info->image->compose=NoCompositeOp;\n if (psd_info->mode == CMYKMode)\n SetImageColorspace(layer_info->image,CMYKColorspace,exception);\n else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) ||\n (psd_info->mode == GrayscaleMode))\n SetImageColorspace(layer_info->image,GRAYColorspace,exception);\n /*\n Set up some hidden attributes for folks that need them.\n */\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.x);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.x\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.y);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.y\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",(double)\n layer_info->opacity);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.opacity\",message);\n (void) SetImageProperty(layer_info->image,\"label\",(char *) layer_info->name,\n exception);",
" status=MagickTrue;\n for (j=0; j < (ssize_t) layer_info->channels; j++)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for channel %.20g\",(double) j);",
" compression=(PSDCompressionType) ReadBlobShort(layer_info->image);\n layer_info->image->compression=ConvertPSDCompression(compression);\n if (layer_info->channel_info[j].type == -1)\n layer_info->image->alpha_trait=BlendPixelTrait;",
" status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,\n compression,exception);",
" if (status == MagickFalse)\n break;\n }",
" if (status != MagickFalse)\n status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,\n MagickFalse,exception);",
" if ((status != MagickFalse) &&\n (layer_info->image->colorspace == CMYKColorspace))\n status=NegateCMYK(layer_info->image,exception);",
" if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))\n {\n const char\n *option;",
" layer_info->mask.image->page.x=layer_info->mask.page.x;\n layer_info->mask.image->page.y=layer_info->mask.page.y;\n /* Do not composite the mask when it is disabled */\n if ((layer_info->mask.flags & 0x02) == 0x02)\n layer_info->mask.image->compose=NoCompositeOp;\n else\n status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,\n layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,\n exception);\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if (IsStringTrue(option) != MagickFalse)\n PreservePSDOpacityMask(image,layer_info,exception);\n layer_info->mask.image=DestroyImage(layer_info->mask.image);\n }",
" return(status);\n}",
"static MagickBooleanType ReadPSDLayersInternal(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n char\n type[4];",
" LayerInfo\n *layer_info;",
" MagickSizeType\n size;",
" MagickBooleanType\n status;",
" register ssize_t\n i;",
" ssize_t\n count,\n j,\n number_layers;",
" size=GetPSDSize(psd_info,image);\n if (size == 0)\n {\n /*\n Skip layers & masks.\n */\n (void) ReadBlobLong(image);\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n status=MagickFalse;\n if ((count == 0) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(MagickTrue);\n else\n {\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n if ((count != 0) && (LocaleNCompare(type,\"Lr16\",4) == 0))\n size=GetPSDSize(psd_info,image);\n else\n return(MagickTrue);\n }\n }\n status=MagickTrue;\n if (size != 0)\n {\n layer_info=(LayerInfo *) NULL;\n number_layers=(short) ReadBlobShort(image);",
" if (number_layers < 0)\n {\n /*\n The first alpha channel in the merged result contains the\n transparency data for the merged result.\n */\n number_layers=MagickAbsoluteValue(number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" negative layer count corrected for\");\n image->alpha_trait=BlendPixelTrait;\n }",
" /*\n We only need to know if the image has an alpha channel\n */\n if (skip_layers != MagickFalse)\n return(MagickTrue);",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image contains %.20g layers\",(double) number_layers);",
" if (number_layers == 0)\n ThrowBinaryException(CorruptImageError,\"InvalidNumberOfLayers\",\n image->filename);",
" layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,\n sizeof(*layer_info));\n if (layer_info == (LayerInfo *) NULL)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of LayerInfo failed\");\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n (void) ResetMagickMemory(layer_info,0,(size_t) number_layers*\n sizeof(*layer_info));",
" for (i=0; i < number_layers; i++)\n {\n ssize_t\n x,\n y;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading layer #%.20g\",(double) i+1);\n layer_info[i].page.y=ReadBlobSignedLong(image);\n layer_info[i].page.x=ReadBlobSignedLong(image);\n y=ReadBlobSignedLong(image);\n x=ReadBlobSignedLong(image);\n layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);\n layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);\n layer_info[i].channels=ReadBlobShort(image);\n if (layer_info[i].channels > MaxPSDChannels)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"MaximumChannelsExceeded\",\n image->filename);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g\",\n (double) layer_info[i].page.x,(double) layer_info[i].page.y,\n (double) layer_info[i].page.height,(double)\n layer_info[i].page.width,(double) layer_info[i].channels);\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);\n layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,\n image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" channel[%.20g]: type=%.20g, size=%.20g\",(double) j,\n (double) layer_info[i].channel_info[j].type,\n (double) layer_info[i].channel_info[j].size);\n }\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n if ((count == 0) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer type was %.4s instead of 8BIM\", type);\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);\n ReversePSDString(image,layer_info[i].blendkey,4);\n layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n layer_info[i].clipping=(unsigned char) ReadBlobByte(image);\n layer_info[i].flags=(unsigned char) ReadBlobByte(image);\n layer_info[i].visible=!(layer_info[i].flags & 0x02);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s\",\n layer_info[i].blendkey,(double) layer_info[i].opacity,\n layer_info[i].clipping ? \"true\" : \"false\",layer_info[i].flags,\n layer_info[i].visible ? \"true\" : \"false\");\n (void) ReadBlobByte(image); /* filler */",
" size=ReadBlobLong(image);\n if (size != 0)\n {\n MagickSizeType\n combined_length,\n length;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer contains additional info\");\n length=ReadBlobLong(image);\n combined_length=length+4;\n if (length != 0)\n {\n /*\n Layer mask info.\n */\n layer_info[i].mask.page.y=ReadBlobSignedLong(image);\n layer_info[i].mask.page.x=ReadBlobSignedLong(image);\n layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-\n layer_info[i].mask.page.y);\n layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)-\n layer_info[i].mask.page.x);\n layer_info[i].mask.background=(unsigned char) ReadBlobByte(\n image);\n layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);\n if (!(layer_info[i].mask.flags & 0x01))\n {\n layer_info[i].mask.page.y=layer_info[i].mask.page.y-\n layer_info[i].page.y;\n layer_info[i].mask.page.x=layer_info[i].mask.page.x-\n layer_info[i].page.x;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g\",\n (double) layer_info[i].mask.page.x,(double)\n layer_info[i].mask.page.y,(double)\n layer_info[i].mask.page.width,(double)\n layer_info[i].mask.page.height,(double) ((MagickOffsetType)\n length)-18);\n /*\n Skip over the rest of the layer mask information.\n */\n if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=ReadBlobLong(image);\n combined_length+=length+4;\n if (length != 0)\n {\n /*\n Layer blending ranges info.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer blending ranges: length=%.20g\",(double)\n ((MagickOffsetType) length));",
" /*\n We read it, but don't use it...\n */\n for (j=0; j < (ssize_t) length; j+=8)\n {\n size_t blend_source=ReadBlobLong(image);\n size_t blend_dest=ReadBlobLong(image);\n if (EOFBlob(image) != MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"InsufficientImageDataInFile\",image->filename);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" source(%x), dest(%x)\",(unsigned int)\n blend_source,(unsigned int) blend_dest);\n }",
" }\n /*\n Layer name.\n */\n length=(MagickSizeType) (unsigned char) ReadBlobByte(image);\n combined_length+=length+1;\n if (length > 0)\n (void) ReadBlob(image,(size_t) length++,layer_info[i].name);\n layer_info[i].name[length]='\\0';\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer name: %s\",layer_info[i].name);\n if ((length % 4) != 0)\n {\n length=4-(length % 4);\n combined_length+=length;\n /* Skip over the padding of the layer name */\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=(MagickSizeType) size-combined_length;\n if (length > 0)\n {\n unsigned char\n *info;",
" if (length > GetBlobSize(image))\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"InsufficientImageDataInFile\",image->filename);\n }\n layer_info[i].info=AcquireStringInfo((const size_t) length);\n info=GetStringInfoDatum(layer_info[i].info);\n (void) ReadBlob(image,(const size_t) length,info);\n }\n }\n }",
" for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is empty\");\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n continue;\n }",
" /*\n Allocate layered image.\n */\n layer_info[i].image=CloneImage(image,layer_info[i].page.width,\n layer_info[i].page.height,MagickFalse,exception);\n if (layer_info[i].image == (Image *) NULL)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of image for layer %.20g failed\",(double) i);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }",
" if (layer_info[i].info != (StringInfo *) NULL)\n {\n (void) SetImageProfile(layer_info[i].image,\"psd:additional-info\",\n layer_info[i].info,exception);\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }\n }",
" if (image_info->ping == MagickFalse)\n {\n for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=0; j < layer_info[i].channels; j++)\n {\n if (DiscardBlobBytes(image,(MagickSizeType)\n layer_info[i].channel_info[j].size) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n continue;\n }",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for layer %.20g\",(double) i);",
" status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],\n exception);\n if (status == MagickFalse)\n break;",
" status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)\n number_layers);\n if (status == MagickFalse)\n break;\n }\n }",
" if (status != MagickFalse)\n {\n for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=i; j < number_layers - 1; j++)\n layer_info[j] = layer_info[j+1];\n number_layers--;\n i--;\n }\n }",
" if (number_layers > 0)\n {\n for (i=0; i < number_layers; i++)\n {\n if (i > 0)\n layer_info[i].image->previous=layer_info[i-1].image;\n if (i < (number_layers-1))\n layer_info[i].image->next=layer_info[i+1].image;\n layer_info[i].image->page=layer_info[i].page;\n }\n image->next=layer_info[0].image;\n layer_info[0].image->previous=image;\n }\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n }\n else\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n }",
" return(status);\n}",
"ModuleExport MagickBooleanType ReadPSDLayers(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n PolicyDomain\n domain;",
" PolicyRights\n rights;",
" domain=CoderPolicyDomain;\n rights=ReadPolicyRights;\n if (IsRightsAuthorized(domain,rights,\"PSD\") == MagickFalse)\n return(MagickFalse);\n return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers,\n exception));\n}",
"static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,\n Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickOffsetType\n *sizes;",
" MagickBooleanType\n status;",
" PSDCompressionType\n compression;",
" register ssize_t\n i;",
" compression=(PSDCompressionType) ReadBlobMSBShort(image);\n image->compression=ConvertPSDCompression(compression);",
" if (compression != Raw && compression != RLE)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n TypeWarning,\"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n return(MagickFalse);\n }",
" sizes=(MagickOffsetType *) NULL;\n if (compression == RLE)\n {\n sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }",
" status=MagickTrue;\n for (i=0; i < (ssize_t) psd_info->channels; i++)\n {\n if (compression == RLE)\n status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows),\n exception);\n else\n status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);",
" if (status != MagickFalse)\n status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);",
" if (status == MagickFalse)\n break;\n }",
" if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))\n status=NegateCMYK(image,exception);",
" if (status != MagickFalse)\n status=CorrectPSDAlphaBlend(image_info,image,exception);",
" sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);",
" return(status);\n}",
"static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;",
" MagickBooleanType\n has_merged_image,\n skip_layers;",
" MagickOffsetType\n offset;",
" MagickSizeType\n length;",
" MagickBooleanType\n status;",
" PSDInfo\n psd_info;",
" register ssize_t\n i;",
" ssize_t\n count;",
" unsigned char\n *data;",
" /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);",
" image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read image header.\n */\n image->endian=MSBEndian;\n count=ReadBlob(image,4,(unsigned char *) psd_info.signature);\n psd_info.version=ReadBlobMSBShort(image);\n if ((count == 0) || (LocaleNCompare(psd_info.signature,\"8BPS\",4) != 0) ||\n ((psd_info.version != 1) && (psd_info.version != 2)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlob(image,6,psd_info.reserved);\n psd_info.channels=ReadBlobMSBShort(image);\n if (psd_info.channels > MaxPSDChannels)\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n psd_info.rows=ReadBlobMSBLong(image);\n psd_info.columns=ReadBlobMSBLong(image);\n if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||\n (psd_info.columns > 30000)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.depth=ReadBlobMSBShort(image);\n if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.mode=ReadBlobMSBShort(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s\",\n (double) psd_info.columns,(double) psd_info.rows,(double)\n psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)\n psd_info.mode));\n /*\n Initialize image.\n */\n image->depth=psd_info.depth;\n image->columns=psd_info.columns;\n image->rows=psd_info.rows;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (SetImageBackgroundColor(image,exception) == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (psd_info.mode == LabMode)\n SetImageColorspace(image,LabColorspace,exception);\n if (psd_info.mode == CMYKMode)\n {\n SetImageColorspace(image,CMYKColorspace,exception);\n if (psd_info.channels > 4)\n SetImageAlphaChannel(image,ActivateAlphaChannel,exception);\n }\n else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||\n (psd_info.mode == DuotoneMode))\n {\n status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,\n exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image colormap allocated\");\n SetImageColorspace(image,GRAYColorspace,exception);\n if (psd_info.channels > 1)\n SetImageAlphaChannel(image,ActivateAlphaChannel,exception);\n }\n else\n if (psd_info.channels > 3)\n SetImageAlphaChannel(image,ActivateAlphaChannel,exception);\n /*\n Read PSD raster colormap only present for indexed and duotone images.\n */\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading colormap\");\n if (psd_info.mode == DuotoneMode)\n {\n /*\n Duotone image data; the format of this data is undocumented.\n */\n data=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*data));\n if (data == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ReadBlob(image,(size_t) length,data);\n data=(unsigned char *) RelinquishMagickMemory(data);\n }\n else\n {\n size_t\n number_colors;",
" /*\n Read PSD raster colormap.\n */\n number_colors=length/3;\n if (number_colors > 65536)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n has_merged_image=MagickTrue;\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n unsigned char\n *blocks;",
" /*\n Image resources block.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading image resource blocks - %.20g bytes\",(double)\n ((MagickOffsetType) length));\n if (length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*blocks));\n if (blocks == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,(size_t) length,blocks);\n if ((count != (ssize_t) length) || (length < 4) ||\n (LocaleNCompare((char *) blocks,\"8BIM\",4) != 0))\n {\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,\n exception);\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n }\n /*\n Layer and mask block.\n */\n length=GetPSDSize(&psd_info,image);\n if (length == 8)\n {\n length=ReadBlobMSBLong(image);\n length=ReadBlobMSBLong(image);\n }\n offset=TellBlob(image);\n skip_layers=MagickFalse;\n if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&\n (has_merged_image != MagickFalse))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" read composite only\");\n skip_layers=MagickTrue;\n }\n if (length == 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has no layers\");\n }\n else\n {\n if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers,\n exception) != MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }",
" /*\n Skip the rest of the layer and mask information.\n */\n SeekBlob(image,offset+length,SEEK_SET);\n }\n /*\n If we are only \"pinging\" the image, then we're done - so return.\n */\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read the precombined layer, present for PSD < 4 compatibility.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading the precombined layer\");\n if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))\n has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,\n &psd_info,exception);\n if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&\n (length != 0))\n {\n SeekBlob(image,offset,SEEK_SET);\n status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse,\n exception);\n if (status != MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n if (has_merged_image == MagickFalse)\n {\n Image\n *merged;",
" if (GetImageListLength(image) == 1)\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n SetImageAlphaChannel(image,TransparentAlphaChannel,exception);\n image->background_color.alpha=TransparentAlpha;\n image->background_color.alpha_trait=BlendPixelTrait;\n merged=MergeImageLayers(image,FlattenLayer,exception);\n ReplaceImageInList(&image,merged);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% RegisterPSDImage() adds properties for the PSD image format to\n% the list of supported formats. The properties include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterPSDImage method is:\n%\n% size_t RegisterPSDImage(void)\n%\n*/\nModuleExport size_t RegisterPSDImage(void)\n{\n MagickInfo\n *entry;",
" entry=AcquireMagickInfo(\"PSD\",\"PSB\",\"Adobe Large Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PSD\",\"PSD\",\"Adobe Photoshop bitmap\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% UnregisterPSDImage() removes format registrations made by the\n% PSD module from the list of supported formats.\n%\n% The format of the UnregisterPSDImage method is:\n%\n% UnregisterPSDImage(void)\n%\n*/\nModuleExport void UnregisterPSDImage(void)\n{\n (void) UnregisterMagickInfo(\"PSB\");\n (void) UnregisterMagickInfo(\"PSD\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.\n%\n% The format of the WritePSDImage method is:\n%\n% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: the image info.\n%\n% o image: The image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/",
"static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,\n const size_t offset)\n{\n if (psd_info->version == 1)\n return(WriteBlobMSBShort(image,(unsigned short) offset));\n return(WriteBlobMSBLong(image,(unsigned short) offset));\n}",
"static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickSizeType offset)\n{\n MagickSizeType\n current_offset;",
" ssize_t\n result;",
" current_offset=TellBlob(image);\n SeekBlob(image,offset,SEEK_SET);\n if (psd_info->version == 1)\n result=WriteBlobMSBShort(image,(unsigned short) size);\n else\n result=(WriteBlobMSBLong(image,(unsigned short) size));\n SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}",
"static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size)\n{\n if (psd_info->version == 1)\n return(WriteBlobMSBLong(image,(unsigned int) size));\n return(WriteBlobMSBLongLong(image,size));\n}",
"static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickSizeType offset)\n{\n MagickSizeType\n current_offset;",
" ssize_t\n result;",
" current_offset=TellBlob(image);\n SeekBlob(image,offset,SEEK_SET);\n if (psd_info->version == 1)\n result=WriteBlobMSBLong(image,(unsigned int) size);\n else\n result=WriteBlobMSBLongLong(image,size);\n SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}",
"static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,\n const unsigned char *pixels,unsigned char *compact_pixels,\n ExceptionInfo *exception)\n{\n int\n count;",
" register ssize_t\n i,\n j;",
" register unsigned char\n *q;",
" unsigned char\n *packbits;",
" /*\n Compress pixels with Packbits encoding.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(pixels != (unsigned char *) NULL);\n assert(compact_pixels != (unsigned char *) NULL);\n packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));\n if (packbits == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n q=compact_pixels;\n for (i=(ssize_t) length; i != 0; )\n {\n switch (i)\n {\n case 1:\n {\n i--;\n *q++=(unsigned char) 0;\n *q++=(*pixels);\n break;\n }\n case 2:\n {\n i-=2;\n *q++=(unsigned char) 1;\n *q++=(*pixels);\n *q++=pixels[1];\n break;\n }\n case 3:\n {\n i-=3;\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n *q++=(unsigned char) ((256-3)+1);\n *q++=(*pixels);\n break;\n }\n *q++=(unsigned char) 2;\n *q++=(*pixels);\n *q++=pixels[1];\n *q++=pixels[2];\n break;\n }\n default:\n {\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n /*\n Packed run.\n */\n count=3;\n while (((ssize_t) count < i) && (*pixels == *(pixels+count)))\n {\n count++;\n if (count >= 127)\n break;\n }\n i-=count;\n *q++=(unsigned char) ((256-count)+1);\n *q++=(*pixels);\n pixels+=count;\n break;\n }\n /*\n Literal run.\n */\n count=0;\n while ((*(pixels+count) != *(pixels+count+1)) ||\n (*(pixels+count+1) != *(pixels+count+2)))\n {\n packbits[count+1]=pixels[count];\n count++;\n if (((ssize_t) count >= (i-3)) || (count >= 127))\n break;\n }\n i-=count;\n *packbits=(unsigned char) (count-1);\n for (j=0; j <= (ssize_t) count; j++)\n *q++=packbits[j];\n pixels+=count;\n break;\n }\n }\n }\n *q++=(unsigned char) 128; /* EOD marker */\n packbits=(unsigned char *) RelinquishMagickMemory(packbits);\n return((size_t) (q-compact_pixels));\n}",
"static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,\n const Image *next_image,const ssize_t channels)\n{\n size_t\n length;",
" ssize_t\n i,\n y;",
" if (next_image->compression == RLECompression)\n {\n length=WriteBlobMSBShort(image,RLE);\n for (i=0; i < channels; i++)\n for (y=0; y < (ssize_t) next_image->rows; y++)\n length+=SetPSDOffset(psd_info,image,0);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (next_image->compression == ZipCompression)\n length=WriteBlobMSBShort(image,ZipWithoutPrediction);\n#endif\n else\n length=WriteBlobMSBShort(image,Raw);\n return(length);\n}",
"static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n int\n y;",
" MagickBooleanType\n monochrome;",
" QuantumInfo\n *quantum_info;",
" register const Quantum\n *p;",
" register ssize_t\n i;",
" size_t\n count,\n length;",
" unsigned char\n *pixels;",
"#ifdef MAGICKCORE_ZLIB_DELEGATE",
"#define CHUNK 16384",
" int\n flush,\n level;",
" unsigned char\n *compressed_pixels;",
" z_stream\n stream;",
" compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,\n sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n ResetMagickMemory(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (next_image->compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (next_image->compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) CHUNK;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) CHUNK-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\n}",
"static unsigned char *AcquireCompactPixels(const Image *image,\n ExceptionInfo *exception)\n{\n size_t\n packet_size;",
" unsigned char\n *compact_pixels;",
" packet_size=image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) AcquireQuantumMemory((9*\n image->columns)+1,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n }\n return(compact_pixels);\n}",
"static size_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n Image\n *mask;",
" MagickOffsetType\n rows_offset;",
" size_t\n channels,\n count,\n length,\n offset_length;",
" unsigned char\n *compact_pixels;",
" count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(next_image,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if (next_image->storage_class != PseudoClass)\n {\n if (IsImageGray(next_image) == MagickFalse)\n channels=next_image->colorspace == CMYKColorspace ? 4 : 3;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if (next_image->storage_class == PseudoClass)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsImageGray(next_image) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);",
" length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;",
" length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;",
" length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;",
" if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (separate != MagickFalse)\n {\n const char\n *property;",
" property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n exception);\n if (mask != (Image *) NULL)\n {\n if (mask->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\n}",
"static size_t WritePascalString(Image *image,const char *value,size_t padding)\n{\n size_t\n count,\n length;",
" register ssize_t\n i;",
" /*\n Max length is 255.\n */\n count=0;\n length=(strlen(value) > 255UL ) ? 255UL : strlen(value);\n if (length == 0)\n count+=WriteBlobByte(image,0);\n else\n {\n count+=WriteBlobByte(image,(unsigned char) length);\n count+=WriteBlob(image,length,(const unsigned char *) value);\n }\n length++;\n if ((length % padding) == 0)\n return(count);\n for (i=0; i < (ssize_t) (padding-(length % padding)); i++)\n count+=WriteBlobByte(image,0);\n return(count);\n}",
"static void WriteResolutionResourceBlock(Image *image)\n{\n double\n x_resolution,\n y_resolution;",
" unsigned short\n units;",
" if (image->units == PixelsPerCentimeterResolution)\n {\n x_resolution=2.54*65536.0*image->resolution.x+0.5;\n y_resolution=2.54*65536.0*image->resolution.y+0.5;\n units=2;\n }\n else\n {\n x_resolution=65536.0*image->resolution.x+0.5;\n y_resolution=65536.0*image->resolution.y+0.5;\n units=1;\n }\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x03ED);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,16); /* resource size */\n (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */\n (void) WriteBlobMSBShort(image,units); /* width unit */\n (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */\n (void) WriteBlobMSBShort(image,units); /* height unit */\n}",
"static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,\n const signed short channel)\n{\n size_t\n count;",
" count=WriteBlobMSBSignedShort(image,channel);\n count+=SetPSDSize(psd_info,image,0);\n return(count);\n}",
"static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)\n{\n register const unsigned char\n *p;",
" size_t\n length;",
" unsigned char\n *datum;",
" unsigned int\n count,\n long_sans;",
" unsigned short\n id,\n short_sans;",
" length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n register unsigned char\n *q;",
" q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n if (id == 0x0000040f)\n {\n ssize_t\n quantum;",
" quantum=PSDQuantum(count)+12;\n if ((quantum >= 12) && (quantum < (ssize_t) length))\n {\n if ((q+quantum < (datum+length-16)))\n (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum));\n SetStringInfoLength(bim_profile,length-quantum);\n }\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}",
"static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)\n{\n register const unsigned char\n *p;",
" size_t\n length;",
" unsigned char\n *datum;",
" unsigned int\n count,\n long_sans;",
" unsigned short\n id,\n short_sans;",
" length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n register unsigned char\n *q;",
" ssize_t\n cnt;",
" q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n return;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n cnt=PSDQuantum(count);\n if (cnt < 0)\n return;\n if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))\n {\n (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));\n SetStringInfoLength(bim_profile,length-(cnt+12));\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}",
"static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n#define PSDKeySize 5\n#define PSDAllowedLength 36",
" char\n key[PSDKeySize];",
" /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */\n const char\n allowed[PSDAllowedLength][PSDKeySize] = {\n \"blnc\", \"blwh\", \"brit\", \"brst\", \"clbl\", \"clrL\", \"curv\", \"expA\", \"FMsk\",\n \"GdFl\", \"grdm\", \"hue \", \"hue2\", \"infx\", \"knko\", \"lclr\", \"levl\", \"lnsr\",\n \"lfx2\", \"luni\", \"lrFX\", \"lspf\", \"lyid\", \"lyvr\", \"mixr\", \"nvrt\", \"phfl\",\n \"post\", \"PtFl\", \"selc\", \"shpa\", \"sn2P\", \"SoCo\", \"thrs\", \"tsly\", \"vibA\"\n },\n *option;",
" const StringInfo\n *info;",
" MagickBooleanType\n found;",
" register size_t\n i;",
" size_t\n remaining_length,\n length;",
" StringInfo\n *profile;",
" unsigned char\n *p;",
" unsigned int\n size;",
" info=GetImageProfile(image,\"psd:additional-info\");\n if (info == (const StringInfo *) NULL)\n return((const StringInfo *) NULL);\n option=GetImageOption(image_info,\"psd:additional-info\");\n if (LocaleCompare(option,\"all\") == 0)\n return(info);\n if (LocaleCompare(option,\"selective\") != 0)\n {\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n return(DestroyStringInfo(profile));\n }\n length=GetStringInfoLength(info);\n p=GetStringInfoDatum(info);\n remaining_length=length;\n length=0;\n while (remaining_length >= 12)\n {\n /* skip over signature */\n p+=4;\n key[0]=(*p++);\n key[1]=(*p++);\n key[2]=(*p++);\n key[3]=(*p++);\n key[4]='\\0';\n size=(unsigned int) (*p++) << 24;\n size|=(unsigned int) (*p++) << 16;\n size|=(unsigned int) (*p++) << 8;\n size|=(unsigned int) (*p++);\n size=size & 0xffffffff;\n remaining_length-=12;\n if ((size_t) size > remaining_length)\n return((const StringInfo *) NULL);\n found=MagickFalse;\n for (i=0; i < PSDAllowedLength; i++)\n {\n if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)\n continue;",
" found=MagickTrue;\n break;\n }\n remaining_length-=(size_t) size;\n if (found == MagickFalse)\n {\n if (remaining_length > 0)\n p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length);\n continue;\n }\n length+=(size_t) size+12;\n p+=size;\n }\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n if (length == 0)\n return(DestroyStringInfo(profile));\n SetStringInfoLength(profile,(const size_t) length);\n SetImageProfile(image,\"psd:additional-info\",info,exception);\n return(profile);\n}",
"static MagickBooleanType WritePSDImage(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n char\n layer_name[MagickPathExtent];",
" const char\n *property;",
" const StringInfo\n *icc_profile,\n *info;",
" Image\n *base_image,\n *next_image;",
" MagickBooleanType\n status;",
" MagickOffsetType\n *layer_size_offsets,\n size_offset;",
" PSDInfo\n psd_info;",
" register ssize_t\n i;",
" size_t\n layer_count,\n layer_index,\n length,\n name_length,\n num_channels,\n packet_size,\n rounded_size,\n size;",
" StringInfo\n *bim_profile;",
" /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n packet_size=(size_t) (image->depth > 8 ? 6 : 3);\n if (image->alpha_trait != UndefinedPixelTrait)\n packet_size+=image->depth > 8 ? 2 : 1;\n psd_info.version=1;\n if ((LocaleCompare(image_info->magick,\"PSB\") == 0) ||\n (image->columns > 30000) || (image->rows > 30000))\n psd_info.version=2;\n (void) WriteBlob(image,4,(const unsigned char *) \"8BPS\");\n (void) WriteBlobMSBShort(image,psd_info.version); /* version */\n for (i=1; i <= 6; i++)\n (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */\n /* When the image has a color profile it won't be converted to gray scale */\n if ((GetImageProfile(image,\"icc\") == (StringInfo *) NULL) &&\n (SetImageGray(image,exception) != MagickFalse))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n if ((image_info->type != TrueColorType) && (image_info->type !=\n TrueColorAlphaType) && (image->storage_class == PseudoClass))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n {\n if (image->storage_class == PseudoClass)\n (void) SetImageStorageClass(image,DirectClass,exception);\n if (image->colorspace != CMYKColorspace)\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);\n else\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);\n }\n (void) WriteBlobMSBShort(image,(unsigned short) num_channels);\n (void) WriteBlobMSBLong(image,(unsigned int) image->rows);\n (void) WriteBlobMSBLong(image,(unsigned int) image->columns);\n if (IsImageGray(image) != MagickFalse)\n {\n MagickBooleanType\n monochrome;",
" /*\n Write depth & mode.\n */\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));\n }\n else\n {\n (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==\n PseudoClass ? 8 : image->depth > 8 ? 16 : 8));",
" if (((image_info->colorspace != UndefinedColorspace) ||\n (image->colorspace != CMYKColorspace)) &&\n (image_info->colorspace != CMYKColorspace))\n {\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) WriteBlobMSBShort(image,(unsigned short)\n (image->storage_class == PseudoClass ? IndexedMode : RGBMode));\n }\n else\n {\n if (image->colorspace != CMYKColorspace)\n (void) TransformImageColorspace(image,CMYKColorspace,exception);\n (void) WriteBlobMSBShort(image,CMYKMode);\n }\n }\n if ((IsImageGray(image) != MagickFalse) ||\n (image->storage_class == DirectClass) || (image->colors > 256))\n (void) WriteBlobMSBLong(image,0);\n else\n {\n /*\n Write PSD raster colormap.\n */\n (void) WriteBlobMSBLong(image,768);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n image->colormap[i].green));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n }\n /*\n Image resource block.\n */\n length=28; /* 0x03EB */\n bim_profile=(StringInfo *) GetImageProfile(image,\"8bim\");\n icc_profile=GetImageProfile(image,\"icc\");\n if (bim_profile != (StringInfo *) NULL)\n {\n bim_profile=CloneStringInfo(bim_profile);\n if (icc_profile != (StringInfo *) NULL)\n RemoveICCProfileFromResourceBlock(bim_profile);\n RemoveResolutionFromResourceBlock(bim_profile);\n length+=PSDQuantum(GetStringInfoLength(bim_profile));\n }\n if (icc_profile != (const StringInfo *) NULL)\n length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n WriteResolutionResourceBlock(image);\n if (bim_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,GetStringInfoLength(bim_profile),\n GetStringInfoDatum(bim_profile));\n bim_profile=DestroyStringInfo(bim_profile);\n }\n if (icc_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x0000040F);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(\n icc_profile));\n (void) WriteBlob(image,GetStringInfoLength(icc_profile),\n GetStringInfoDatum(icc_profile));\n if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=\n PSDQuantum(GetStringInfoLength(icc_profile)))\n (void) WriteBlobByte(image,0);\n }\n base_image=GetNextImageInList(image);\n if (base_image == (Image *) NULL)\n base_image=image;\n size=0;\n size_offset=TellBlob(image);\n SetPSDSize(&psd_info,image,0);\n SetPSDSize(&psd_info,image,0);\n layer_count=0;\n for (next_image=base_image; next_image != NULL; )\n {\n layer_count++;\n next_image=GetNextImageInList(next_image);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);\n else\n size+=WriteBlobMSBShort(image,(unsigned short) layer_count);\n layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(\n (size_t) layer_count,sizeof(MagickOffsetType));\n if (layer_size_offsets == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n layer_index=0;\n for (next_image=base_image; next_image != NULL; )\n {\n Image\n *mask;",
" unsigned char\n default_color;",
" unsigned short\n channels,\n total_channels;",
" mask=(Image *) NULL;\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n default_color=0;\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);\n default_color=strlen(property) == 9 ? 255 : 0;\n }\n size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);\n size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);\n size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+\n next_image->rows));\n size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+\n next_image->columns));\n channels=1U;\n if ((next_image->storage_class != PseudoClass) &&\n (IsImageGray(next_image) == MagickFalse))\n channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;\n total_channels=channels;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n total_channels++;\n if (mask != (Image *) NULL)\n total_channels++;\n size+=WriteBlobMSBShort(image,total_channels);\n layer_size_offsets[layer_index++]=TellBlob(image);\n for (i=0; i < (ssize_t) channels; i++)\n size+=WriteChannelSize(&psd_info,image,(signed short) i);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n size+=WriteChannelSize(&psd_info,image,-1);\n if (mask != (Image *) NULL)\n size+=WriteChannelSize(&psd_info,image,-2);\n size+=WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n size+=WriteBlob(image,4,(const unsigned char *)\n CompositeOperatorToPSDBlendMode(next_image->compose));\n property=GetImageArtifact(next_image,\"psd:layer.opacity\");\n if (property != (const char *) NULL)\n {\n Quantum\n opacity;",
" opacity=(Quantum) StringToInteger(property);\n size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));\n (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);\n }\n else\n size+=WriteBlobByte(image,255);\n size+=WriteBlobByte(image,0);\n size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?\n 1 << 0x02 : 1); /* layer properties - visible, etc. */\n size+=WriteBlobByte(image,0);\n info=GetAdditionalInformation(image_info,next_image,exception);\n property=(const char *) GetImageProperty(next_image,\"label\",exception);\n if (property == (const char *) NULL)\n {\n (void) FormatLocaleString(layer_name,MagickPathExtent,\"L%.20g\",\n (double) layer_index);\n property=layer_name;\n }\n name_length=strlen(property)+1;\n if ((name_length % 4) != 0)\n name_length+=(4-(name_length % 4));\n if (info != (const StringInfo *) NULL)\n name_length+=GetStringInfoLength(info);\n name_length+=8;\n if (mask != (Image *) NULL)\n name_length+=20;\n size+=WriteBlobMSBLong(image,(unsigned int) name_length);\n if (mask == (Image *) NULL)\n size+=WriteBlobMSBLong(image,0);\n else\n {\n if (mask->compose != NoCompositeOp)\n (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(\n default_color),MagickTrue,exception);\n mask->page.y+=image->page.y;\n mask->page.x+=image->page.x;\n size+=WriteBlobMSBLong(image,20);\n size+=WriteBlobMSBSignedLong(image,mask->page.y);\n size+=WriteBlobMSBSignedLong(image,mask->page.x);\n size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+\n mask->page.y);\n size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+\n mask->page.x);\n size+=WriteBlobByte(image,default_color);\n size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);\n size+=WriteBlobMSBShort(image,0);\n }\n size+=WriteBlobMSBLong(image,0);\n size+=WritePascalString(image,property,4);\n if (info != (const StringInfo *) NULL)\n size+=WriteBlob(image,GetStringInfoLength(info),\n GetStringInfoDatum(info));\n next_image=GetNextImageInList(next_image);\n }\n /*\n Now the image data!\n */\n next_image=base_image;\n layer_index=0;\n while (next_image != NULL)\n {\n length=WritePSDChannels(&psd_info,image_info,image,next_image,\n layer_size_offsets[layer_index++],MagickTrue,exception);\n if (length == 0)\n {\n status=MagickFalse;\n break;\n }\n size+=length;\n next_image=GetNextImageInList(next_image);\n }\n (void) WriteBlobMSBLong(image,0); /* user mask data */\n /*\n Write the total size\n */\n size_offset+=WritePSDSize(&psd_info,image,size+\n (psd_info.version == 1 ? 8 : 16),size_offset);\n if ((size/2) != ((size+1)/2))\n rounded_size=size+1;\n else\n rounded_size=size;\n (void) WritePSDSize(&psd_info,image,rounded_size,size_offset);\n layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(\n layer_size_offsets);\n /*\n Remove the opacity mask from the registry\n */\n next_image=base_image;\n while (next_image != (Image *) NULL)\n {\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n DeleteImageRegistry(property);\n next_image=GetNextImageInList(next_image);\n }\n /*\n Write composite image.\n */\n if (status != MagickFalse)\n {\n CompressionType\n compression;",
" compression=image->compression;\n if (image->compression == ZipCompression)\n image->compression=RLECompression;\n if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,\n exception) == 0)\n status=MagickFalse;\n image->compression=compression;\n }\n (void) CloseBlob(image);\n return(status);\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,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [1727], "buggy_code_start_loc": [1331], "filenames": ["coders/psd.c"], "fixing_code_end_loc": [1715], "fixing_code_start_loc": [1331], "message": "In coders/psd.c in ImageMagick 7.0.7-0 Q16, a DoS in ReadPSDLayersInternal() due to lack of an EOF (End of File) check might cause huge CPU consumption. When a crafted PSD file, which claims a large \"length\" field in the header but does not contain sufficient backing data, is provided, the loop over \"length\" would consume huge CPU resources, since there is no EOF check inside the loop.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.7-0:*:*:*:*:*:*:*", "matchCriteriaId": "ACD6A151-47EB-4305-B4CB-F9003BC2E5DE", "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:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"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": "In coders/psd.c in ImageMagick 7.0.7-0 Q16, a DoS in ReadPSDLayersInternal() due to lack of an EOF (End of File) check might cause huge CPU consumption. When a crafted PSD file, which claims a large \"length\" field in the header but does not contain sufficient backing data, is provided, the loop over \"length\" would consume huge CPU resources, since there is no EOF check inside the loop."}, {"lang": "es", "value": "En coders/psd.c en ImageMagick 7.0.7-0 Q16, una denegaci\u00f3n de servicio en ReadPSDLayersInternal() por una falta de chequeos EOF (End of File) podr\u00eda provocar un enorme consumo de recursos de la CPU. Cuando se proporciona un archivo PSD manipulado que pide un campo \"length\" grande en la cabecera pero no contiene suficientes datos de respaldo, el bucle en \"length\" consumir\u00eda una gran cantidad de recursos de CPU, ya que el bucle no contiene ning\u00fan chequeo EOF."}], "evaluatorComment": null, "id": "CVE-2017-14174", "lastModified": "2020-10-23T18:16:50.530", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-09-07T06:29:00.390", "references": [{"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/04a567494786d5bb50894fc8bb8fea0cf496bea8"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/f68a98a9d385838a1c73ec960a14102949940a64"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/issues/714"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/05/msg00015.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2020/09/msg00007.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201711-07"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3681-1/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-834"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/04a567494786d5bb50894fc8bb8fea0cf496bea8"}, "type": "CWE-834"}
| 310
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% PPPP SSSSS DDDD %\n% P P SS D D %\n% PPPP SSS D D %\n% P SS D D %\n% P SSSSS DDDD %\n% %\n% %\n% Read/Write Adobe Photoshop Image Format %\n% %\n% Software Design %\n% Cristy %\n% Leonard Rosenthol %\n% July 1992 %\n% Dirk Lemstra %\n% December 2013 %\n% %\n% %\n% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% https://www.imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/channel.h\"\n#include \"MagickCore/colormap.h\"\n#include \"MagickCore/colormap-private.h\"\n#include \"MagickCore/colorspace.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/enhance.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/log.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/policy.h\"\n#include \"MagickCore/profile.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/registry.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/string-private.h\"\n#include \"MagickCore/thread-private.h\"\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n#include <zlib.h>\n#endif\n#include \"psd-private.h\"",
"/*\n Define declaractions.\n*/\n#define MaxPSDChannels 56\n#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)\n\f\n/*\n Enumerated declaractions.\n*/\ntypedef enum\n{\n Raw = 0,\n RLE = 1,\n ZipWithoutPrediction = 2,\n ZipWithPrediction = 3\n} PSDCompressionType;",
"typedef enum\n{\n BitmapMode = 0,\n GrayscaleMode = 1,\n IndexedMode = 2,\n RGBMode = 3,\n CMYKMode = 4,\n MultichannelMode = 7,\n DuotoneMode = 8,\n LabMode = 9\n} PSDImageType;\n\f\n/*\n Typedef declaractions.\n*/\ntypedef struct _ChannelInfo\n{\n short int\n type;",
" size_t\n size;\n} ChannelInfo;",
"typedef struct _MaskInfo\n{\n Image\n *image;",
" RectangleInfo\n page;",
" unsigned char\n background,\n flags;\n} MaskInfo;",
"typedef struct _LayerInfo\n{\n ChannelInfo\n channel_info[MaxPSDChannels];",
" char\n blendkey[4];",
" Image\n *image;",
" MaskInfo\n mask;",
" Quantum\n opacity;",
" RectangleInfo\n page;",
" size_t\n offset_x,\n offset_y;",
" unsigned char\n clipping,\n flags,\n name[256],\n visible;",
" unsigned short\n channels;",
" StringInfo\n *info;\n} LayerInfo;",
"/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I s P S D %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% IsPSD()() returns MagickTrue if the image format type, identified by the\n% magick string, is PSD.\n%\n% The format of the IsPSD method is:\n%\n% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n%\n% A description of each parameter follows:\n%\n% o magick: compare image format pattern against these bytes.\n%\n% o length: Specifies the length of the magick string.\n%\n*/\nstatic MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n{\n if (length < 4)\n return(MagickFalse);\n if (LocaleNCompare((const char *) magick,\"8BPS\",4) == 0)\n return(MagickTrue);\n return(MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadPSDImage() reads an Adobe Photoshop image file and returns it. It\n% allocates the memory necessary for the new Image structure and returns a\n% pointer to the new image.\n%\n% The format of the ReadPSDImage method is:\n%\n% Image *ReadPSDImage(image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/",
"static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op)\n{\n const char\n *blend_mode;",
" switch (op)\n {\n case ColorBurnCompositeOp: blend_mode = \"idiv\"; break;\n case ColorDodgeCompositeOp: blend_mode = \"div \"; break;\n case ColorizeCompositeOp: blend_mode = \"colr\"; break;\n case DarkenCompositeOp: blend_mode = \"dark\"; break;\n case DifferenceCompositeOp: blend_mode = \"diff\"; break;\n case DissolveCompositeOp: blend_mode = \"diss\"; break;\n case ExclusionCompositeOp: blend_mode = \"smud\"; break;\n case HardLightCompositeOp: blend_mode = \"hLit\"; break;\n case HardMixCompositeOp: blend_mode = \"hMix\"; break;\n case HueCompositeOp: blend_mode = \"hue \"; break;\n case LightenCompositeOp: blend_mode = \"lite\"; break;\n case LinearBurnCompositeOp: blend_mode = \"lbrn\"; break;\n case LinearDodgeCompositeOp:blend_mode = \"lddg\"; break;\n case LinearLightCompositeOp:blend_mode = \"lLit\"; break;\n case LuminizeCompositeOp: blend_mode = \"lum \"; break;\n case MultiplyCompositeOp: blend_mode = \"mul \"; break;\n case OverCompositeOp: blend_mode = \"norm\"; break;\n case OverlayCompositeOp: blend_mode = \"over\"; break;\n case PinLightCompositeOp: blend_mode = \"pLit\"; break;\n case SaturateCompositeOp: blend_mode = \"sat \"; break;\n case ScreenCompositeOp: blend_mode = \"scrn\"; break;\n case SoftLightCompositeOp: blend_mode = \"sLit\"; break;\n case VividLightCompositeOp: blend_mode = \"vLit\"; break;\n default: blend_mode = \"norm\";\n }\n return(blend_mode);\n}",
"/*\n For some reason Photoshop seems to blend semi-transparent pixels with white.\n This method reverts the blending. This can be disabled by setting the\n option 'psd:alpha-unblend' to off.\n*/\nstatic MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,\n Image *image,ExceptionInfo* exception)\n{\n const char\n *option;",
" MagickBooleanType\n status;",
" ssize_t\n y;",
" if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)\n return(MagickTrue);\n option=GetImageOption(image_info,\"psd:alpha-unblend\");\n if (IsStringFalse(option) != MagickFalse)\n return(MagickTrue);\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" register ssize_t\n x;",
" if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;",
" register ssize_t\n i;",
" gamma=QuantumScale*GetPixelAlpha(image, q);\n if (gamma != 0.0 && gamma != 1.0)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n if (channel != AlphaPixelChannel)\n q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);\n }\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }",
" return(status);\n}",
"static inline CompressionType ConvertPSDCompression(\n PSDCompressionType compression)\n{\n switch (compression)\n {\n case RLE:\n return RLECompression;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n return ZipCompression;\n default:\n return NoCompression;\n }\n}",
"static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,\n MagickBooleanType revert,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" ssize_t\n y;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying layer opacity %.20g\", (double) opacity);\n if (opacity == OpaqueAlpha)\n return(MagickTrue);\n image->alpha_trait=BlendPixelTrait;\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" register ssize_t\n x;",
" if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (revert == MagickFalse)\n SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*\n opacity),q);\n else if (opacity > 0)\n SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/\n (MagickRealType) opacity)),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }",
" return(status);\n}",
"static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,\n Quantum background,MagickBooleanType revert,ExceptionInfo *exception)\n{\n Image\n *complete_mask;",
" MagickBooleanType\n status;",
" PixelInfo\n color;",
" ssize_t\n y;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying opacity mask\");\n complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue,\n exception);\n complete_mask->alpha_trait=BlendPixelTrait;\n GetPixelInfo(complete_mask,&color);\n color.red=background;\n SetImageColor(complete_mask,&color,exception);\n status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,\n mask->page.x-image->page.x,mask->page.y-image->page.y,exception);\n if (status == MagickFalse)\n {\n complete_mask=DestroyImage(complete_mask);\n return(status);\n }\n image->alpha_trait=BlendPixelTrait;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static,4) shared(status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;",
" register Quantum\n *p;",
" register ssize_t\n x;",
" if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);\n if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n MagickRealType\n alpha,\n intensity;",
" alpha=GetPixelAlpha(image,q);\n intensity=GetPixelIntensity(complete_mask,p);\n if (revert == MagickFalse)\n SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);\n else if (intensity > 0)\n SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);\n q+=GetPixelChannels(image);\n p+=GetPixelChannels(complete_mask);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }\n complete_mask=DestroyImage(complete_mask);\n return(status);\n}",
"static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,\n ExceptionInfo *exception)\n{\n char\n *key;",
" RandomInfo\n *random_info;",
" StringInfo\n *key_info;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" preserving opacity mask\");\n random_info=AcquireRandomInfo();\n key_info=GetRandomKey(random_info,2+1);\n key=(char *) GetStringInfoDatum(key_info);\n key[8]=layer_info->mask.background;\n key[9]='\\0';\n layer_info->mask.image->page.x+=layer_info->page.x;\n layer_info->mask.image->page.y+=layer_info->page.y;\n (void) SetImageRegistry(ImageRegistryType,(const char *) key,\n layer_info->mask.image,exception);\n (void) SetImageArtifact(layer_info->image,\"psd:opacity-mask\",\n (const char *) key);\n key_info=DestroyStringInfo(key_info);\n random_info=DestroyRandomInfo(random_info);\n}",
"static ssize_t DecodePSDPixels(const size_t number_compact_pixels,\n const unsigned char *compact_pixels,const ssize_t depth,\n const size_t number_pixels,unsigned char *pixels)\n{\n#define CheckNumberCompactPixels \\\n if (packets == 0) \\\n return(i); \\\n packets--",
"#define CheckNumberPixels(count) \\\n if (((ssize_t) i + count) > (ssize_t) number_pixels) \\\n return(i); \\\n i+=count",
" int\n pixel;",
" register ssize_t\n i,\n j;",
" size_t\n length;",
" ssize_t\n packets;",
" packets=(ssize_t) number_compact_pixels;\n for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )\n {\n packets--;\n length=(size_t) (*compact_pixels++);\n if (length == 128)\n continue;\n if (length > 128)\n {\n length=256-length+1;\n CheckNumberCompactPixels;\n pixel=(*compact_pixels++);\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(unsigned char) ((pixel >> 6) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 4) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 2) & 0x03);\n *pixels++=(unsigned char) ((pixel & 0x03) & 0x03);\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(unsigned char) ((pixel >> 4) & 0xff);\n *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(unsigned char) pixel;\n break;\n }\n }\n }\n continue;\n }\n length++;\n for (j=0; j < (ssize_t) length; j++)\n {\n CheckNumberCompactPixels;\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(*compact_pixels >> 6) & 0x03;\n *pixels++=(*compact_pixels >> 4) & 0x03;\n *pixels++=(*compact_pixels >> 2) & 0x03;\n *pixels++=(*compact_pixels & 0x03) & 0x03;\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(*compact_pixels >> 4) & 0xff;\n *pixels++=(*compact_pixels & 0x0f) & 0xff;\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(*compact_pixels);\n break;\n }\n }\n compact_pixels++;\n }\n }\n return(i);\n}",
"static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,\n const ssize_t number_layers)\n{\n ssize_t\n i;",
" for (i=0; i<number_layers; i++)\n {\n if (layer_info[i].image != (Image *) NULL)\n layer_info[i].image=DestroyImage(layer_info[i].image);\n if (layer_info[i].mask.image != (Image *) NULL)\n layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }",
" return (LayerInfo *) RelinquishMagickMemory(layer_info);\n}",
"static inline size_t GetPSDPacketSize(Image *image)\n{\n if (image->storage_class == PseudoClass)\n {\n if (image->colors > 256)\n return(2);\n else if (image->depth > 8)\n return(2);\n }\n else\n if (image->depth > 8)\n return(2);",
" return(1);\n}",
"static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)\n{\n if (psd_info->version == 1)\n return((MagickSizeType) ReadBlobLong(image));\n return((MagickSizeType) ReadBlobLongLong(image));\n}",
"static inline size_t GetPSDRowSize(Image *image)\n{\n if (image->depth == 1)\n return(((image->columns+7)/8)*GetPSDPacketSize(image));\n else\n return(image->columns*GetPSDPacketSize(image));\n}",
"static const char *ModeToString(PSDImageType type)\n{\n switch (type)\n {\n case BitmapMode: return \"Bitmap\";\n case GrayscaleMode: return \"Grayscale\";\n case IndexedMode: return \"Indexed\";\n case RGBMode: return \"RGB\";\n case CMYKMode: return \"CMYK\";\n case MultichannelMode: return \"Multichannel\";\n case DuotoneMode: return \"Duotone\";\n case LabMode: return \"L*A*B\";\n default: return \"unknown\";\n }\n}",
"static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)\n{\n ChannelType\n channel_mask;",
" MagickBooleanType\n status;",
" channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~\n AlphaChannel));\n status=NegateImage(image,MagickFalse,exception);\n (void) SetImageChannelMask(image,channel_mask);\n return(status);\n}",
"static void ParseImageResourceBlocks(Image *image,\n const unsigned char *blocks,size_t length,\n MagickBooleanType *has_merged_image,ExceptionInfo *exception)\n{\n const unsigned char\n *p;",
" StringInfo\n *profile;",
" unsigned char\n name_length;",
" unsigned int\n count;",
" unsigned short\n id,\n short_sans;",
" if (length < 16)\n return;\n profile=BlobToStringInfo((const unsigned char *) NULL,length);\n SetStringInfoDatum(profile,blocks);\n (void) SetImageProfile(image,\"8bim\",profile,exception);\n profile=DestroyStringInfo(profile);\n for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); )\n {\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p+=4;\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushCharPixel(p,&name_length);\n if ((name_length % 2) == 0)\n name_length++;\n p+=name_length;\n if (p > (blocks+length-4))\n return;\n p=PushLongPixel(MSBEndian,p,&count);\n if ((p+count) > (blocks+length))\n return;\n switch (id)\n {\n case 0x03ed:\n {\n char\n value[MagickPathExtent];",
" unsigned short\n resolution;",
" /*\n Resolution info.\n */\n if (count < 16)\n return;\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.x=(double) resolution;\n (void) FormatLocaleString(value,MagickPathExtent,\"%g\",\n image->resolution.x);\n (void) SetImageProperty(image,\"tiff:XResolution\",value,exception);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.y=(double) resolution;\n (void) FormatLocaleString(value,MagickPathExtent,\"%g\",\n image->resolution.y);\n (void) SetImageProperty(image,\"tiff:YResolution\",value,exception);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n image->units=PixelsPerInchResolution;\n break;\n }\n case 0x0421:\n {\n if ((count > 3) && (*(p+4) == 0))\n *has_merged_image=MagickFalse;\n p+=count;\n break;\n }\n default:\n {\n p+=count;\n break;\n }\n }\n if ((count & 0x01) != 0)\n p++;\n }\n return;\n}",
"static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)\n{\n if (mode == (const char *) NULL)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"norm\",4) == 0)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"mul \",4) == 0)\n return(MultiplyCompositeOp);\n if (LocaleNCompare(mode,\"diss\",4) == 0)\n return(DissolveCompositeOp);\n if (LocaleNCompare(mode,\"diff\",4) == 0)\n return(DifferenceCompositeOp);\n if (LocaleNCompare(mode,\"dark\",4) == 0)\n return(DarkenCompositeOp);\n if (LocaleNCompare(mode,\"lite\",4) == 0)\n return(LightenCompositeOp);\n if (LocaleNCompare(mode,\"hue \",4) == 0)\n return(HueCompositeOp);\n if (LocaleNCompare(mode,\"sat \",4) == 0)\n return(SaturateCompositeOp);\n if (LocaleNCompare(mode,\"colr\",4) == 0)\n return(ColorizeCompositeOp);\n if (LocaleNCompare(mode,\"lum \",4) == 0)\n return(LuminizeCompositeOp);\n if (LocaleNCompare(mode,\"scrn\",4) == 0)\n return(ScreenCompositeOp);\n if (LocaleNCompare(mode,\"over\",4) == 0)\n return(OverlayCompositeOp);\n if (LocaleNCompare(mode,\"hLit\",4) == 0)\n return(HardLightCompositeOp);\n if (LocaleNCompare(mode,\"sLit\",4) == 0)\n return(SoftLightCompositeOp);\n if (LocaleNCompare(mode,\"smud\",4) == 0)\n return(ExclusionCompositeOp);\n if (LocaleNCompare(mode,\"div \",4) == 0)\n return(ColorDodgeCompositeOp);\n if (LocaleNCompare(mode,\"idiv\",4) == 0)\n return(ColorBurnCompositeOp);\n if (LocaleNCompare(mode,\"lbrn\",4) == 0)\n return(LinearBurnCompositeOp);\n if (LocaleNCompare(mode,\"lddg\",4) == 0)\n return(LinearDodgeCompositeOp);\n if (LocaleNCompare(mode,\"lLit\",4) == 0)\n return(LinearLightCompositeOp);\n if (LocaleNCompare(mode,\"vLit\",4) == 0)\n return(VividLightCompositeOp);\n if (LocaleNCompare(mode,\"pLit\",4) == 0)\n return(PinLightCompositeOp);\n if (LocaleNCompare(mode,\"hMix\",4) == 0)\n return(HardMixCompositeOp);\n return(OverCompositeOp);\n}",
"static inline void ReversePSDString(Image *image,char *p,size_t length)\n{\n char\n *q;",
" if (image->endian == MSBEndian)\n return;",
" q=p+length;\n for(--q; p < q; ++p, --q)\n {\n *p = *p ^ *q,\n *q = *p ^ *q,\n *p = *p ^ *q;\n }\n}",
"static inline void SetPSDPixel(Image *image,const size_t channels,\n const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,\n ExceptionInfo *exception)\n{\n if (image->storage_class == PseudoClass)\n {\n PixelInfo\n *color;",
" if (type == 0)\n {\n if (packet_size == 1)\n SetPixelIndex(image,ScaleQuantumToChar(pixel),q);\n else\n SetPixelIndex(image,ScaleQuantumToShort(pixel),q);\n }\n color=image->colormap+(ssize_t) ConstrainColormapIndex(image,\n GetPixelIndex(image,q),exception);\n if ((type == 0) && (channels > 1))\n return;\n else\n color->alpha=(MagickRealType) pixel;\n SetPixelViaPixelInfo(image,color,q);\n return;\n }\n switch (type)\n {\n case -1:\n {\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case -2:\n case 0:\n {\n SetPixelRed(image,pixel,q);\n break;\n }\n case 1:\n {\n SetPixelGreen(image,pixel,q);\n break;\n }\n case 2:\n {\n SetPixelBlue(image,pixel,q);\n break;\n }\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,pixel,q);\n else\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case 4:\n {\n if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&\n (channels > 3))\n break;\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n }\n}",
"static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const size_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;",
" register const unsigned char\n *p;",
" register Quantum\n *q;",
" register ssize_t\n x;",
" size_t\n packet_size;",
" unsigned short\n nibble;",
" p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n if (image->depth > 1)\n {\n SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);\n q+=GetPixelChannels(image);\n }\n else\n {\n ssize_t\n bit,\n number_bits;",
" number_bits=image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit = 0; bit < number_bits; bit++)\n {\n SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)\n & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);\n q+=GetPixelChannels(image);\n x++;\n }\n if (x != (ssize_t) image->columns)\n x--;\n continue;\n }\n }\n return(SyncAuthenticPixels(image,exception));\n}",
"static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,\n const ssize_t type,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" size_t\n count,\n row_size;",
" ssize_t\n y;",
" unsigned char\n *pixels;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RAW\");",
" row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);",
" status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;",
" count=ReadBlob(image,row_size,pixels);\n if (count != row_size)\n break;",
" status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);\n if (status == MagickFalse)\n break;\n }",
" pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}",
"static inline MagickOffsetType *ReadPSDRLESizes(Image *image,\n const PSDInfo *psd_info,const size_t size)\n{\n MagickOffsetType\n *sizes;",
" ssize_t\n y;",
" sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));\n if(sizes != (MagickOffsetType *) NULL)\n {\n for (y=0; y < (ssize_t) size; y++)\n {\n if (psd_info->version == 1)\n sizes[y]=(MagickOffsetType) ReadBlobShort(image);\n else\n sizes[y]=(MagickOffsetType) ReadBlobLong(image);\n }\n }\n return sizes;\n}",
"static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,\n const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" size_t\n length,\n row_size;",
" ssize_t\n count,\n y;",
" unsigned char\n *compact_pixels,\n *pixels;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RLE compressed\");",
" row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);",
" length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n if ((MagickOffsetType) length < sizes[y])\n length=(size_t) sizes[y];",
" if (length > row_size + 256) // arbitrary number\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"InvalidLength\",image->filename);\n }",
" compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }",
" (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));",
" status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;",
" count=ReadBlob(image,(size_t) sizes[y],compact_pixels);\n if (count != (ssize_t) sizes[y])\n break;",
" count=DecodePSDPixels((size_t) sizes[y],compact_pixels,\n (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);\n if (count != (ssize_t) row_size)\n break;",
" status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,\n exception);\n if (status == MagickFalse)\n break;\n }",
" compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}",
"#ifdef MAGICKCORE_ZLIB_DELEGATE\nstatic MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,\n const ssize_t type,const PSDCompressionType compression,\n const size_t compact_size,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;",
" register unsigned char\n *p;",
" size_t\n count,\n length,\n packet_size,\n row_size;",
" ssize_t\n y;",
" unsigned char\n *compact_pixels,\n *pixels;",
" z_stream\n stream;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is ZIP compressed\");",
" compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,\n sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);",
" packet_size=GetPSDPacketSize(image);\n row_size=image->columns*packet_size;\n count=image->rows*row_size;",
" pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }",
" ResetMagickMemory(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n stream.next_in=(Bytef *)compact_pixels;\n stream.avail_in=(uInt) compact_size;\n stream.next_out=(Bytef *)pixels;\n stream.avail_out=(uInt) count;",
" if (inflateInit(&stream) == Z_OK)\n {\n int\n ret;",
" while (stream.avail_out > 0)\n {\n ret=inflate(&stream,Z_SYNC_FLUSH);\n if ((ret != Z_OK) && (ret != Z_STREAM_END))\n {\n (void) inflateEnd(&stream);\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(MagickFalse);\n }\n }\n (void) inflateEnd(&stream);\n }",
" if (compression == ZipWithPrediction)\n {\n p=pixels;\n while (count > 0)\n {\n length=image->columns;\n while (--length)\n {\n if (packet_size == 2)\n {\n p[2]+=p[0]+((p[1]+p[3]) >> 8);\n p[3]+=p[1];\n }\n else\n *(p+1)+=*p;\n p+=packet_size;\n }\n p+=packet_size;\n count-=row_size;\n }\n }",
" status=MagickTrue;\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=ReadPSDChannelPixels(image,channels,y,type,p,exception);\n if (status == MagickFalse)\n break;",
" p+=row_size;\n }",
" compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}\n#endif",
"static MagickBooleanType ReadPSDChannel(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,\n const size_t channel,const PSDCompressionType compression,\n ExceptionInfo *exception)\n{\n Image\n *channel_image,\n *mask;",
" MagickOffsetType\n offset;",
" MagickBooleanType\n status;",
" channel_image=image;\n mask=(Image *) NULL;\n if ((layer_info->channel_info[channel].type < -1) &&\n (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))\n {\n const char\n *option;",
" /*\n Ignore mask that is not a user supplied layer mask, if the mask is\n disabled or if the flags have unsupported values.\n */\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if ((layer_info->channel_info[channel].type != -2) ||\n (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&\n (IsStringTrue(option) == MagickFalse)))",
" {\n SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);\n return(MagickTrue);\n }",
" mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n if (mask != (Image *) NULL)\n {\n SetImageType(mask,GrayscaleType,exception);\n channel_image=mask;\n }\n }",
" offset=TellBlob(image);\n status=MagickFalse;\n switch(compression)\n {\n case Raw:\n status=ReadPSDChannelRaw(channel_image,psd_info->channels,\n layer_info->channel_info[channel].type,exception);\n break;\n case RLE:\n {\n MagickOffsetType\n *sizes;",
" sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n status=ReadPSDChannelRLE(channel_image,psd_info,\n layer_info->channel_info[channel].type,sizes,exception);\n sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);\n }\n break;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n status=ReadPSDChannelZip(channel_image,layer_info->channels,\n layer_info->channel_info[channel].type,compression,\n layer_info->channel_info[channel].size-2,exception);\n#else\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateWarning,\"DelegateLibrarySupportNotBuiltIn\",\n \"'%s' (ZLIB)\",image->filename);\n#endif\n break;\n default:\n (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,\n \"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n break;\n }",
" SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);\n if (status == MagickFalse)\n {\n if (mask != (Image *) NULL)\n DestroyImage(mask);\n ThrowBinaryException(CoderError,\"UnableToDecompressImage\",\n image->filename);\n }\n layer_info->mask.image=mask;\n return(status);\n}",
"static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,\n const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)\n{\n char\n message[MagickPathExtent];",
" MagickBooleanType\n status;",
" PSDCompressionType\n compression;",
" ssize_t\n j;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" setting up new layer image\");\n if (psd_info->mode != IndexedMode)\n (void) SetImageBackgroundColor(layer_info->image,exception);\n layer_info->image->compose=PSDBlendModeToCompositeOperator(\n layer_info->blendkey);\n if (layer_info->visible == MagickFalse)\n layer_info->image->compose=NoCompositeOp;\n if (psd_info->mode == CMYKMode)\n SetImageColorspace(layer_info->image,CMYKColorspace,exception);\n else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) ||\n (psd_info->mode == GrayscaleMode))\n SetImageColorspace(layer_info->image,GRAYColorspace,exception);\n /*\n Set up some hidden attributes for folks that need them.\n */\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.x);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.x\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.y);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.y\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",(double)\n layer_info->opacity);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.opacity\",message);\n (void) SetImageProperty(layer_info->image,\"label\",(char *) layer_info->name,\n exception);",
" status=MagickTrue;\n for (j=0; j < (ssize_t) layer_info->channels; j++)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for channel %.20g\",(double) j);",
" compression=(PSDCompressionType) ReadBlobShort(layer_info->image);\n layer_info->image->compression=ConvertPSDCompression(compression);\n if (layer_info->channel_info[j].type == -1)\n layer_info->image->alpha_trait=BlendPixelTrait;",
" status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j,\n compression,exception);",
" if (status == MagickFalse)\n break;\n }",
" if (status != MagickFalse)\n status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,\n MagickFalse,exception);",
" if ((status != MagickFalse) &&\n (layer_info->image->colorspace == CMYKColorspace))\n status=NegateCMYK(layer_info->image,exception);",
" if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))\n {\n const char\n *option;",
" layer_info->mask.image->page.x=layer_info->mask.page.x;\n layer_info->mask.image->page.y=layer_info->mask.page.y;\n /* Do not composite the mask when it is disabled */\n if ((layer_info->mask.flags & 0x02) == 0x02)\n layer_info->mask.image->compose=NoCompositeOp;\n else\n status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,\n layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,\n exception);\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if (IsStringTrue(option) != MagickFalse)\n PreservePSDOpacityMask(image,layer_info,exception);\n layer_info->mask.image=DestroyImage(layer_info->mask.image);\n }",
" return(status);\n}",
"static MagickBooleanType ReadPSDLayersInternal(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n char\n type[4];",
" LayerInfo\n *layer_info;",
" MagickSizeType\n size;",
" MagickBooleanType\n status;",
" register ssize_t\n i;",
" ssize_t\n count,\n j,\n number_layers;",
" size=GetPSDSize(psd_info,image);\n if (size == 0)\n {\n /*\n Skip layers & masks.\n */\n (void) ReadBlobLong(image);\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n status=MagickFalse;\n if ((count == 0) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(MagickTrue);\n else\n {\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n if ((count != 0) && (LocaleNCompare(type,\"Lr16\",4) == 0))\n size=GetPSDSize(psd_info,image);\n else\n return(MagickTrue);\n }\n }\n status=MagickTrue;\n if (size != 0)\n {\n layer_info=(LayerInfo *) NULL;\n number_layers=(short) ReadBlobShort(image);",
" if (number_layers < 0)\n {\n /*\n The first alpha channel in the merged result contains the\n transparency data for the merged result.\n */\n number_layers=MagickAbsoluteValue(number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" negative layer count corrected for\");\n image->alpha_trait=BlendPixelTrait;\n }",
" /*\n We only need to know if the image has an alpha channel\n */\n if (skip_layers != MagickFalse)\n return(MagickTrue);",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image contains %.20g layers\",(double) number_layers);",
" if (number_layers == 0)\n ThrowBinaryException(CorruptImageError,\"InvalidNumberOfLayers\",\n image->filename);",
" layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,\n sizeof(*layer_info));\n if (layer_info == (LayerInfo *) NULL)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of LayerInfo failed\");\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n (void) ResetMagickMemory(layer_info,0,(size_t) number_layers*\n sizeof(*layer_info));",
" for (i=0; i < number_layers; i++)\n {\n ssize_t\n x,\n y;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading layer #%.20g\",(double) i+1);\n layer_info[i].page.y=ReadBlobSignedLong(image);\n layer_info[i].page.x=ReadBlobSignedLong(image);\n y=ReadBlobSignedLong(image);\n x=ReadBlobSignedLong(image);\n layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);\n layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);\n layer_info[i].channels=ReadBlobShort(image);\n if (layer_info[i].channels > MaxPSDChannels)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"MaximumChannelsExceeded\",\n image->filename);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g\",\n (double) layer_info[i].page.x,(double) layer_info[i].page.y,\n (double) layer_info[i].page.height,(double)\n layer_info[i].page.width,(double) layer_info[i].channels);\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);\n layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,\n image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" channel[%.20g]: type=%.20g, size=%.20g\",(double) j,\n (double) layer_info[i].channel_info[j].type,\n (double) layer_info[i].channel_info[j].size);\n }\n count=ReadBlob(image,4,(unsigned char *) type);\n ReversePSDString(image,type,4);\n if ((count == 0) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer type was %.4s instead of 8BIM\", type);\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);\n ReversePSDString(image,layer_info[i].blendkey,4);\n layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n layer_info[i].clipping=(unsigned char) ReadBlobByte(image);\n layer_info[i].flags=(unsigned char) ReadBlobByte(image);\n layer_info[i].visible=!(layer_info[i].flags & 0x02);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s\",\n layer_info[i].blendkey,(double) layer_info[i].opacity,\n layer_info[i].clipping ? \"true\" : \"false\",layer_info[i].flags,\n layer_info[i].visible ? \"true\" : \"false\");\n (void) ReadBlobByte(image); /* filler */",
" size=ReadBlobLong(image);\n if (size != 0)\n {\n MagickSizeType\n combined_length,\n length;",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer contains additional info\");\n length=ReadBlobLong(image);\n combined_length=length+4;\n if (length != 0)\n {\n /*\n Layer mask info.\n */\n layer_info[i].mask.page.y=ReadBlobSignedLong(image);\n layer_info[i].mask.page.x=ReadBlobSignedLong(image);\n layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-\n layer_info[i].mask.page.y);\n layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)-\n layer_info[i].mask.page.x);\n layer_info[i].mask.background=(unsigned char) ReadBlobByte(\n image);\n layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);\n if (!(layer_info[i].mask.flags & 0x01))\n {\n layer_info[i].mask.page.y=layer_info[i].mask.page.y-\n layer_info[i].page.y;\n layer_info[i].mask.page.x=layer_info[i].mask.page.x-\n layer_info[i].page.x;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g\",\n (double) layer_info[i].mask.page.x,(double)\n layer_info[i].mask.page.y,(double)\n layer_info[i].mask.page.width,(double)\n layer_info[i].mask.page.height,(double) ((MagickOffsetType)\n length)-18);\n /*\n Skip over the rest of the layer mask information.\n */\n if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=ReadBlobLong(image);\n combined_length+=length+4;\n if (length != 0)\n {\n /*\n Layer blending ranges info.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer blending ranges: length=%.20g\",(double)\n ((MagickOffsetType) length));",
" if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }",
" }\n /*\n Layer name.\n */\n length=(MagickSizeType) (unsigned char) ReadBlobByte(image);\n combined_length+=length+1;\n if (length > 0)\n (void) ReadBlob(image,(size_t) length++,layer_info[i].name);\n layer_info[i].name[length]='\\0';\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer name: %s\",layer_info[i].name);\n if ((length % 4) != 0)\n {\n length=4-(length % 4);\n combined_length+=length;\n /* Skip over the padding of the layer name */\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=(MagickSizeType) size-combined_length;\n if (length > 0)\n {\n unsigned char\n *info;",
" if (length > GetBlobSize(image))\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"InsufficientImageDataInFile\",image->filename);\n }\n layer_info[i].info=AcquireStringInfo((const size_t) length);\n info=GetStringInfoDatum(layer_info[i].info);\n (void) ReadBlob(image,(const size_t) length,info);\n }\n }\n }",
" for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is empty\");\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n continue;\n }",
" /*\n Allocate layered image.\n */\n layer_info[i].image=CloneImage(image,layer_info[i].page.width,\n layer_info[i].page.height,MagickFalse,exception);\n if (layer_info[i].image == (Image *) NULL)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of image for layer %.20g failed\",(double) i);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }",
" if (layer_info[i].info != (StringInfo *) NULL)\n {\n (void) SetImageProfile(layer_info[i].image,\"psd:additional-info\",\n layer_info[i].info,exception);\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }\n }",
" if (image_info->ping == MagickFalse)\n {\n for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=0; j < layer_info[i].channels; j++)\n {\n if (DiscardBlobBytes(image,(MagickSizeType)\n layer_info[i].channel_info[j].size) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n continue;\n }",
" if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for layer %.20g\",(double) i);",
" status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],\n exception);\n if (status == MagickFalse)\n break;",
" status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)\n number_layers);\n if (status == MagickFalse)\n break;\n }\n }",
" if (status != MagickFalse)\n {\n for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=i; j < number_layers - 1; j++)\n layer_info[j] = layer_info[j+1];\n number_layers--;\n i--;\n }\n }",
" if (number_layers > 0)\n {\n for (i=0; i < number_layers; i++)\n {\n if (i > 0)\n layer_info[i].image->previous=layer_info[i-1].image;\n if (i < (number_layers-1))\n layer_info[i].image->next=layer_info[i+1].image;\n layer_info[i].image->page=layer_info[i].page;\n }\n image->next=layer_info[0].image;\n layer_info[0].image->previous=image;\n }\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n }\n else\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n }",
" return(status);\n}",
"ModuleExport MagickBooleanType ReadPSDLayers(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n PolicyDomain\n domain;",
" PolicyRights\n rights;",
" domain=CoderPolicyDomain;\n rights=ReadPolicyRights;\n if (IsRightsAuthorized(domain,rights,\"PSD\") == MagickFalse)\n return(MagickFalse);\n return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers,\n exception));\n}",
"static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,\n Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickOffsetType\n *sizes;",
" MagickBooleanType\n status;",
" PSDCompressionType\n compression;",
" register ssize_t\n i;",
" compression=(PSDCompressionType) ReadBlobMSBShort(image);\n image->compression=ConvertPSDCompression(compression);",
" if (compression != Raw && compression != RLE)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n TypeWarning,\"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n return(MagickFalse);\n }",
" sizes=(MagickOffsetType *) NULL;\n if (compression == RLE)\n {\n sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }",
" status=MagickTrue;\n for (i=0; i < (ssize_t) psd_info->channels; i++)\n {\n if (compression == RLE)\n status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows),\n exception);\n else\n status=ReadPSDChannelRaw(image,psd_info->channels,i,exception);",
" if (status != MagickFalse)\n status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels);",
" if (status == MagickFalse)\n break;\n }",
" if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))\n status=NegateCMYK(image,exception);",
" if (status != MagickFalse)\n status=CorrectPSDAlphaBlend(image_info,image,exception);",
" sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);",
" return(status);\n}",
"static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;",
" MagickBooleanType\n has_merged_image,\n skip_layers;",
" MagickOffsetType\n offset;",
" MagickSizeType\n length;",
" MagickBooleanType\n status;",
" PSDInfo\n psd_info;",
" register ssize_t\n i;",
" ssize_t\n count;",
" unsigned char\n *data;",
" /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);",
" image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read image header.\n */\n image->endian=MSBEndian;\n count=ReadBlob(image,4,(unsigned char *) psd_info.signature);\n psd_info.version=ReadBlobMSBShort(image);\n if ((count == 0) || (LocaleNCompare(psd_info.signature,\"8BPS\",4) != 0) ||\n ((psd_info.version != 1) && (psd_info.version != 2)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlob(image,6,psd_info.reserved);\n psd_info.channels=ReadBlobMSBShort(image);\n if (psd_info.channels > MaxPSDChannels)\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n psd_info.rows=ReadBlobMSBLong(image);\n psd_info.columns=ReadBlobMSBLong(image);\n if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||\n (psd_info.columns > 30000)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.depth=ReadBlobMSBShort(image);\n if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.mode=ReadBlobMSBShort(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s\",\n (double) psd_info.columns,(double) psd_info.rows,(double)\n psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)\n psd_info.mode));\n /*\n Initialize image.\n */\n image->depth=psd_info.depth;\n image->columns=psd_info.columns;\n image->rows=psd_info.rows;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (SetImageBackgroundColor(image,exception) == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (psd_info.mode == LabMode)\n SetImageColorspace(image,LabColorspace,exception);\n if (psd_info.mode == CMYKMode)\n {\n SetImageColorspace(image,CMYKColorspace,exception);\n if (psd_info.channels > 4)\n SetImageAlphaChannel(image,ActivateAlphaChannel,exception);\n }\n else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||\n (psd_info.mode == DuotoneMode))\n {\n status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,\n exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image colormap allocated\");\n SetImageColorspace(image,GRAYColorspace,exception);\n if (psd_info.channels > 1)\n SetImageAlphaChannel(image,ActivateAlphaChannel,exception);\n }\n else\n if (psd_info.channels > 3)\n SetImageAlphaChannel(image,ActivateAlphaChannel,exception);\n /*\n Read PSD raster colormap only present for indexed and duotone images.\n */\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading colormap\");\n if (psd_info.mode == DuotoneMode)\n {\n /*\n Duotone image data; the format of this data is undocumented.\n */\n data=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*data));\n if (data == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ReadBlob(image,(size_t) length,data);\n data=(unsigned char *) RelinquishMagickMemory(data);\n }\n else\n {\n size_t\n number_colors;",
" /*\n Read PSD raster colormap.\n */\n number_colors=length/3;\n if (number_colors > 65536)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n has_merged_image=MagickTrue;\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n unsigned char\n *blocks;",
" /*\n Image resources block.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading image resource blocks - %.20g bytes\",(double)\n ((MagickOffsetType) length));\n if (length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*blocks));\n if (blocks == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,(size_t) length,blocks);\n if ((count != (ssize_t) length) || (length < 4) ||\n (LocaleNCompare((char *) blocks,\"8BIM\",4) != 0))\n {\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,\n exception);\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n }\n /*\n Layer and mask block.\n */\n length=GetPSDSize(&psd_info,image);\n if (length == 8)\n {\n length=ReadBlobMSBLong(image);\n length=ReadBlobMSBLong(image);\n }\n offset=TellBlob(image);\n skip_layers=MagickFalse;\n if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&\n (has_merged_image != MagickFalse))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" read composite only\");\n skip_layers=MagickTrue;\n }\n if (length == 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has no layers\");\n }\n else\n {\n if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers,\n exception) != MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }",
" /*\n Skip the rest of the layer and mask information.\n */\n SeekBlob(image,offset+length,SEEK_SET);\n }\n /*\n If we are only \"pinging\" the image, then we're done - so return.\n */\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read the precombined layer, present for PSD < 4 compatibility.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading the precombined layer\");\n if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))\n has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,\n &psd_info,exception);\n if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&\n (length != 0))\n {\n SeekBlob(image,offset,SEEK_SET);\n status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse,\n exception);\n if (status != MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n if (has_merged_image == MagickFalse)\n {\n Image\n *merged;",
" if (GetImageListLength(image) == 1)\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n SetImageAlphaChannel(image,TransparentAlphaChannel,exception);\n image->background_color.alpha=TransparentAlpha;\n image->background_color.alpha_trait=BlendPixelTrait;\n merged=MergeImageLayers(image,FlattenLayer,exception);\n ReplaceImageInList(&image,merged);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% RegisterPSDImage() adds properties for the PSD image format to\n% the list of supported formats. The properties include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterPSDImage method is:\n%\n% size_t RegisterPSDImage(void)\n%\n*/\nModuleExport size_t RegisterPSDImage(void)\n{\n MagickInfo\n *entry;",
" entry=AcquireMagickInfo(\"PSD\",\"PSB\",\"Adobe Large Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PSD\",\"PSD\",\"Adobe Photoshop bitmap\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% UnregisterPSDImage() removes format registrations made by the\n% PSD module from the list of supported formats.\n%\n% The format of the UnregisterPSDImage method is:\n%\n% UnregisterPSDImage(void)\n%\n*/\nModuleExport void UnregisterPSDImage(void)\n{\n (void) UnregisterMagickInfo(\"PSB\");\n (void) UnregisterMagickInfo(\"PSD\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.\n%\n% The format of the WritePSDImage method is:\n%\n% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: the image info.\n%\n% o image: The image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/",
"static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,\n const size_t offset)\n{\n if (psd_info->version == 1)\n return(WriteBlobMSBShort(image,(unsigned short) offset));\n return(WriteBlobMSBLong(image,(unsigned short) offset));\n}",
"static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickSizeType offset)\n{\n MagickSizeType\n current_offset;",
" ssize_t\n result;",
" current_offset=TellBlob(image);\n SeekBlob(image,offset,SEEK_SET);\n if (psd_info->version == 1)\n result=WriteBlobMSBShort(image,(unsigned short) size);\n else\n result=(WriteBlobMSBLong(image,(unsigned short) size));\n SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}",
"static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size)\n{\n if (psd_info->version == 1)\n return(WriteBlobMSBLong(image,(unsigned int) size));\n return(WriteBlobMSBLongLong(image,size));\n}",
"static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickSizeType offset)\n{\n MagickSizeType\n current_offset;",
" ssize_t\n result;",
" current_offset=TellBlob(image);\n SeekBlob(image,offset,SEEK_SET);\n if (psd_info->version == 1)\n result=WriteBlobMSBLong(image,(unsigned int) size);\n else\n result=WriteBlobMSBLongLong(image,size);\n SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}",
"static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,\n const unsigned char *pixels,unsigned char *compact_pixels,\n ExceptionInfo *exception)\n{\n int\n count;",
" register ssize_t\n i,\n j;",
" register unsigned char\n *q;",
" unsigned char\n *packbits;",
" /*\n Compress pixels with Packbits encoding.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(pixels != (unsigned char *) NULL);\n assert(compact_pixels != (unsigned char *) NULL);\n packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));\n if (packbits == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n q=compact_pixels;\n for (i=(ssize_t) length; i != 0; )\n {\n switch (i)\n {\n case 1:\n {\n i--;\n *q++=(unsigned char) 0;\n *q++=(*pixels);\n break;\n }\n case 2:\n {\n i-=2;\n *q++=(unsigned char) 1;\n *q++=(*pixels);\n *q++=pixels[1];\n break;\n }\n case 3:\n {\n i-=3;\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n *q++=(unsigned char) ((256-3)+1);\n *q++=(*pixels);\n break;\n }\n *q++=(unsigned char) 2;\n *q++=(*pixels);\n *q++=pixels[1];\n *q++=pixels[2];\n break;\n }\n default:\n {\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n /*\n Packed run.\n */\n count=3;\n while (((ssize_t) count < i) && (*pixels == *(pixels+count)))\n {\n count++;\n if (count >= 127)\n break;\n }\n i-=count;\n *q++=(unsigned char) ((256-count)+1);\n *q++=(*pixels);\n pixels+=count;\n break;\n }\n /*\n Literal run.\n */\n count=0;\n while ((*(pixels+count) != *(pixels+count+1)) ||\n (*(pixels+count+1) != *(pixels+count+2)))\n {\n packbits[count+1]=pixels[count];\n count++;\n if (((ssize_t) count >= (i-3)) || (count >= 127))\n break;\n }\n i-=count;\n *packbits=(unsigned char) (count-1);\n for (j=0; j <= (ssize_t) count; j++)\n *q++=packbits[j];\n pixels+=count;\n break;\n }\n }\n }\n *q++=(unsigned char) 128; /* EOD marker */\n packbits=(unsigned char *) RelinquishMagickMemory(packbits);\n return((size_t) (q-compact_pixels));\n}",
"static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,\n const Image *next_image,const ssize_t channels)\n{\n size_t\n length;",
" ssize_t\n i,\n y;",
" if (next_image->compression == RLECompression)\n {\n length=WriteBlobMSBShort(image,RLE);\n for (i=0; i < channels; i++)\n for (y=0; y < (ssize_t) next_image->rows; y++)\n length+=SetPSDOffset(psd_info,image,0);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (next_image->compression == ZipCompression)\n length=WriteBlobMSBShort(image,ZipWithoutPrediction);\n#endif\n else\n length=WriteBlobMSBShort(image,Raw);\n return(length);\n}",
"static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n int\n y;",
" MagickBooleanType\n monochrome;",
" QuantumInfo\n *quantum_info;",
" register const Quantum\n *p;",
" register ssize_t\n i;",
" size_t\n count,\n length;",
" unsigned char\n *pixels;",
"#ifdef MAGICKCORE_ZLIB_DELEGATE",
"#define CHUNK 16384",
" int\n flush,\n level;",
" unsigned char\n *compressed_pixels;",
" z_stream\n stream;",
" compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,\n sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n ResetMagickMemory(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (next_image->compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (next_image->compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) CHUNK;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) CHUNK-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\n}",
"static unsigned char *AcquireCompactPixels(const Image *image,\n ExceptionInfo *exception)\n{\n size_t\n packet_size;",
" unsigned char\n *compact_pixels;",
" packet_size=image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) AcquireQuantumMemory((9*\n image->columns)+1,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n }\n return(compact_pixels);\n}",
"static size_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n Image\n *mask;",
" MagickOffsetType\n rows_offset;",
" size_t\n channels,\n count,\n length,\n offset_length;",
" unsigned char\n *compact_pixels;",
" count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(next_image,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if (next_image->storage_class != PseudoClass)\n {\n if (IsImageGray(next_image) == MagickFalse)\n channels=next_image->colorspace == CMYKColorspace ? 4 : 3;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if (next_image->storage_class == PseudoClass)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsImageGray(next_image) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);",
" length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;",
" length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;",
" length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;",
" if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate,exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (separate != MagickFalse)\n {\n const char\n *property;",
" property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n exception);\n if (mask != (Image *) NULL)\n {\n if (mask->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\n}",
"static size_t WritePascalString(Image *image,const char *value,size_t padding)\n{\n size_t\n count,\n length;",
" register ssize_t\n i;",
" /*\n Max length is 255.\n */\n count=0;\n length=(strlen(value) > 255UL ) ? 255UL : strlen(value);\n if (length == 0)\n count+=WriteBlobByte(image,0);\n else\n {\n count+=WriteBlobByte(image,(unsigned char) length);\n count+=WriteBlob(image,length,(const unsigned char *) value);\n }\n length++;\n if ((length % padding) == 0)\n return(count);\n for (i=0; i < (ssize_t) (padding-(length % padding)); i++)\n count+=WriteBlobByte(image,0);\n return(count);\n}",
"static void WriteResolutionResourceBlock(Image *image)\n{\n double\n x_resolution,\n y_resolution;",
" unsigned short\n units;",
" if (image->units == PixelsPerCentimeterResolution)\n {\n x_resolution=2.54*65536.0*image->resolution.x+0.5;\n y_resolution=2.54*65536.0*image->resolution.y+0.5;\n units=2;\n }\n else\n {\n x_resolution=65536.0*image->resolution.x+0.5;\n y_resolution=65536.0*image->resolution.y+0.5;\n units=1;\n }\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x03ED);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,16); /* resource size */\n (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */\n (void) WriteBlobMSBShort(image,units); /* width unit */\n (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */\n (void) WriteBlobMSBShort(image,units); /* height unit */\n}",
"static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,\n const signed short channel)\n{\n size_t\n count;",
" count=WriteBlobMSBSignedShort(image,channel);\n count+=SetPSDSize(psd_info,image,0);\n return(count);\n}",
"static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)\n{\n register const unsigned char\n *p;",
" size_t\n length;",
" unsigned char\n *datum;",
" unsigned int\n count,\n long_sans;",
" unsigned short\n id,\n short_sans;",
" length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n register unsigned char\n *q;",
" q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n if (id == 0x0000040f)\n {\n ssize_t\n quantum;",
" quantum=PSDQuantum(count)+12;\n if ((quantum >= 12) && (quantum < (ssize_t) length))\n {\n if ((q+quantum < (datum+length-16)))\n (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum));\n SetStringInfoLength(bim_profile,length-quantum);\n }\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}",
"static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)\n{\n register const unsigned char\n *p;",
" size_t\n length;",
" unsigned char\n *datum;",
" unsigned int\n count,\n long_sans;",
" unsigned short\n id,\n short_sans;",
" length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n register unsigned char\n *q;",
" ssize_t\n cnt;",
" q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n return;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n cnt=PSDQuantum(count);\n if (cnt < 0)\n return;\n if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)))\n {\n (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum));\n SetStringInfoLength(bim_profile,length-(cnt+12));\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}",
"static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n#define PSDKeySize 5\n#define PSDAllowedLength 36",
" char\n key[PSDKeySize];",
" /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */\n const char\n allowed[PSDAllowedLength][PSDKeySize] = {\n \"blnc\", \"blwh\", \"brit\", \"brst\", \"clbl\", \"clrL\", \"curv\", \"expA\", \"FMsk\",\n \"GdFl\", \"grdm\", \"hue \", \"hue2\", \"infx\", \"knko\", \"lclr\", \"levl\", \"lnsr\",\n \"lfx2\", \"luni\", \"lrFX\", \"lspf\", \"lyid\", \"lyvr\", \"mixr\", \"nvrt\", \"phfl\",\n \"post\", \"PtFl\", \"selc\", \"shpa\", \"sn2P\", \"SoCo\", \"thrs\", \"tsly\", \"vibA\"\n },\n *option;",
" const StringInfo\n *info;",
" MagickBooleanType\n found;",
" register size_t\n i;",
" size_t\n remaining_length,\n length;",
" StringInfo\n *profile;",
" unsigned char\n *p;",
" unsigned int\n size;",
" info=GetImageProfile(image,\"psd:additional-info\");\n if (info == (const StringInfo *) NULL)\n return((const StringInfo *) NULL);\n option=GetImageOption(image_info,\"psd:additional-info\");\n if (LocaleCompare(option,\"all\") == 0)\n return(info);\n if (LocaleCompare(option,\"selective\") != 0)\n {\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n return(DestroyStringInfo(profile));\n }\n length=GetStringInfoLength(info);\n p=GetStringInfoDatum(info);\n remaining_length=length;\n length=0;\n while (remaining_length >= 12)\n {\n /* skip over signature */\n p+=4;\n key[0]=(*p++);\n key[1]=(*p++);\n key[2]=(*p++);\n key[3]=(*p++);\n key[4]='\\0';\n size=(unsigned int) (*p++) << 24;\n size|=(unsigned int) (*p++) << 16;\n size|=(unsigned int) (*p++) << 8;\n size|=(unsigned int) (*p++);\n size=size & 0xffffffff;\n remaining_length-=12;\n if ((size_t) size > remaining_length)\n return((const StringInfo *) NULL);\n found=MagickFalse;\n for (i=0; i < PSDAllowedLength; i++)\n {\n if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)\n continue;",
" found=MagickTrue;\n break;\n }\n remaining_length-=(size_t) size;\n if (found == MagickFalse)\n {\n if (remaining_length > 0)\n p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length);\n continue;\n }\n length+=(size_t) size+12;\n p+=size;\n }\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n if (length == 0)\n return(DestroyStringInfo(profile));\n SetStringInfoLength(profile,(const size_t) length);\n SetImageProfile(image,\"psd:additional-info\",info,exception);\n return(profile);\n}",
"static MagickBooleanType WritePSDImage(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n char\n layer_name[MagickPathExtent];",
" const char\n *property;",
" const StringInfo\n *icc_profile,\n *info;",
" Image\n *base_image,\n *next_image;",
" MagickBooleanType\n status;",
" MagickOffsetType\n *layer_size_offsets,\n size_offset;",
" PSDInfo\n psd_info;",
" register ssize_t\n i;",
" size_t\n layer_count,\n layer_index,\n length,\n name_length,\n num_channels,\n packet_size,\n rounded_size,\n size;",
" StringInfo\n *bim_profile;",
" /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n packet_size=(size_t) (image->depth > 8 ? 6 : 3);\n if (image->alpha_trait != UndefinedPixelTrait)\n packet_size+=image->depth > 8 ? 2 : 1;\n psd_info.version=1;\n if ((LocaleCompare(image_info->magick,\"PSB\") == 0) ||\n (image->columns > 30000) || (image->rows > 30000))\n psd_info.version=2;\n (void) WriteBlob(image,4,(const unsigned char *) \"8BPS\");\n (void) WriteBlobMSBShort(image,psd_info.version); /* version */\n for (i=1; i <= 6; i++)\n (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */\n /* When the image has a color profile it won't be converted to gray scale */\n if ((GetImageProfile(image,\"icc\") == (StringInfo *) NULL) &&\n (SetImageGray(image,exception) != MagickFalse))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n if ((image_info->type != TrueColorType) && (image_info->type !=\n TrueColorAlphaType) && (image->storage_class == PseudoClass))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n {\n if (image->storage_class == PseudoClass)\n (void) SetImageStorageClass(image,DirectClass,exception);\n if (image->colorspace != CMYKColorspace)\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);\n else\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);\n }\n (void) WriteBlobMSBShort(image,(unsigned short) num_channels);\n (void) WriteBlobMSBLong(image,(unsigned int) image->rows);\n (void) WriteBlobMSBLong(image,(unsigned int) image->columns);\n if (IsImageGray(image) != MagickFalse)\n {\n MagickBooleanType\n monochrome;",
" /*\n Write depth & mode.\n */\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));\n }\n else\n {\n (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==\n PseudoClass ? 8 : image->depth > 8 ? 16 : 8));",
" if (((image_info->colorspace != UndefinedColorspace) ||\n (image->colorspace != CMYKColorspace)) &&\n (image_info->colorspace != CMYKColorspace))\n {\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) WriteBlobMSBShort(image,(unsigned short)\n (image->storage_class == PseudoClass ? IndexedMode : RGBMode));\n }\n else\n {\n if (image->colorspace != CMYKColorspace)\n (void) TransformImageColorspace(image,CMYKColorspace,exception);\n (void) WriteBlobMSBShort(image,CMYKMode);\n }\n }\n if ((IsImageGray(image) != MagickFalse) ||\n (image->storage_class == DirectClass) || (image->colors > 256))\n (void) WriteBlobMSBLong(image,0);\n else\n {\n /*\n Write PSD raster colormap.\n */\n (void) WriteBlobMSBLong(image,768);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n image->colormap[i].green));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n }\n /*\n Image resource block.\n */\n length=28; /* 0x03EB */\n bim_profile=(StringInfo *) GetImageProfile(image,\"8bim\");\n icc_profile=GetImageProfile(image,\"icc\");\n if (bim_profile != (StringInfo *) NULL)\n {\n bim_profile=CloneStringInfo(bim_profile);\n if (icc_profile != (StringInfo *) NULL)\n RemoveICCProfileFromResourceBlock(bim_profile);\n RemoveResolutionFromResourceBlock(bim_profile);\n length+=PSDQuantum(GetStringInfoLength(bim_profile));\n }\n if (icc_profile != (const StringInfo *) NULL)\n length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n WriteResolutionResourceBlock(image);\n if (bim_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,GetStringInfoLength(bim_profile),\n GetStringInfoDatum(bim_profile));\n bim_profile=DestroyStringInfo(bim_profile);\n }\n if (icc_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x0000040F);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(\n icc_profile));\n (void) WriteBlob(image,GetStringInfoLength(icc_profile),\n GetStringInfoDatum(icc_profile));\n if ((MagickOffsetType) GetStringInfoLength(icc_profile) !=\n PSDQuantum(GetStringInfoLength(icc_profile)))\n (void) WriteBlobByte(image,0);\n }\n base_image=GetNextImageInList(image);\n if (base_image == (Image *) NULL)\n base_image=image;\n size=0;\n size_offset=TellBlob(image);\n SetPSDSize(&psd_info,image,0);\n SetPSDSize(&psd_info,image,0);\n layer_count=0;\n for (next_image=base_image; next_image != NULL; )\n {\n layer_count++;\n next_image=GetNextImageInList(next_image);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n size+=WriteBlobMSBShort(image,-(unsigned short) layer_count);\n else\n size+=WriteBlobMSBShort(image,(unsigned short) layer_count);\n layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(\n (size_t) layer_count,sizeof(MagickOffsetType));\n if (layer_size_offsets == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n layer_index=0;\n for (next_image=base_image; next_image != NULL; )\n {\n Image\n *mask;",
" unsigned char\n default_color;",
" unsigned short\n channels,\n total_channels;",
" mask=(Image *) NULL;\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n default_color=0;\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);\n default_color=strlen(property) == 9 ? 255 : 0;\n }\n size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y);\n size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x);\n size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+\n next_image->rows));\n size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+\n next_image->columns));\n channels=1U;\n if ((next_image->storage_class != PseudoClass) &&\n (IsImageGray(next_image) == MagickFalse))\n channels=next_image->colorspace == CMYKColorspace ? 4U : 3U;\n total_channels=channels;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n total_channels++;\n if (mask != (Image *) NULL)\n total_channels++;\n size+=WriteBlobMSBShort(image,total_channels);\n layer_size_offsets[layer_index++]=TellBlob(image);\n for (i=0; i < (ssize_t) channels; i++)\n size+=WriteChannelSize(&psd_info,image,(signed short) i);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n size+=WriteChannelSize(&psd_info,image,-1);\n if (mask != (Image *) NULL)\n size+=WriteChannelSize(&psd_info,image,-2);\n size+=WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n size+=WriteBlob(image,4,(const unsigned char *)\n CompositeOperatorToPSDBlendMode(next_image->compose));\n property=GetImageArtifact(next_image,\"psd:layer.opacity\");\n if (property != (const char *) NULL)\n {\n Quantum\n opacity;",
" opacity=(Quantum) StringToInteger(property);\n size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));\n (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);\n }\n else\n size+=WriteBlobByte(image,255);\n size+=WriteBlobByte(image,0);\n size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ?\n 1 << 0x02 : 1); /* layer properties - visible, etc. */\n size+=WriteBlobByte(image,0);\n info=GetAdditionalInformation(image_info,next_image,exception);\n property=(const char *) GetImageProperty(next_image,\"label\",exception);\n if (property == (const char *) NULL)\n {\n (void) FormatLocaleString(layer_name,MagickPathExtent,\"L%.20g\",\n (double) layer_index);\n property=layer_name;\n }\n name_length=strlen(property)+1;\n if ((name_length % 4) != 0)\n name_length+=(4-(name_length % 4));\n if (info != (const StringInfo *) NULL)\n name_length+=GetStringInfoLength(info);\n name_length+=8;\n if (mask != (Image *) NULL)\n name_length+=20;\n size+=WriteBlobMSBLong(image,(unsigned int) name_length);\n if (mask == (Image *) NULL)\n size+=WriteBlobMSBLong(image,0);\n else\n {\n if (mask->compose != NoCompositeOp)\n (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(\n default_color),MagickTrue,exception);\n mask->page.y+=image->page.y;\n mask->page.x+=image->page.x;\n size+=WriteBlobMSBLong(image,20);\n size+=WriteBlobMSBSignedLong(image,mask->page.y);\n size+=WriteBlobMSBSignedLong(image,mask->page.x);\n size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+\n mask->page.y);\n size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+\n mask->page.x);\n size+=WriteBlobByte(image,default_color);\n size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0);\n size+=WriteBlobMSBShort(image,0);\n }\n size+=WriteBlobMSBLong(image,0);\n size+=WritePascalString(image,property,4);\n if (info != (const StringInfo *) NULL)\n size+=WriteBlob(image,GetStringInfoLength(info),\n GetStringInfoDatum(info));\n next_image=GetNextImageInList(next_image);\n }\n /*\n Now the image data!\n */\n next_image=base_image;\n layer_index=0;\n while (next_image != NULL)\n {\n length=WritePSDChannels(&psd_info,image_info,image,next_image,\n layer_size_offsets[layer_index++],MagickTrue,exception);\n if (length == 0)\n {\n status=MagickFalse;\n break;\n }\n size+=length;\n next_image=GetNextImageInList(next_image);\n }\n (void) WriteBlobMSBLong(image,0); /* user mask data */\n /*\n Write the total size\n */\n size_offset+=WritePSDSize(&psd_info,image,size+\n (psd_info.version == 1 ? 8 : 16),size_offset);\n if ((size/2) != ((size+1)/2))\n rounded_size=size+1;\n else\n rounded_size=size;\n (void) WritePSDSize(&psd_info,image,rounded_size,size_offset);\n layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(\n layer_size_offsets);\n /*\n Remove the opacity mask from the registry\n */\n next_image=base_image;\n while (next_image != (Image *) NULL)\n {\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n DeleteImageRegistry(property);\n next_image=GetNextImageInList(next_image);\n }\n /*\n Write composite image.\n */\n if (status != MagickFalse)\n {\n CompressionType\n compression;",
" compression=image->compression;\n if (image->compression == ZipCompression)\n image->compression=RLECompression;\n if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,\n exception) == 0)\n status=MagickFalse;\n image->compression=compression;\n }\n (void) CloseBlob(image);\n return(status);\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1727], "buggy_code_start_loc": [1331], "filenames": ["coders/psd.c"], "fixing_code_end_loc": [1715], "fixing_code_start_loc": [1331], "message": "In coders/psd.c in ImageMagick 7.0.7-0 Q16, a DoS in ReadPSDLayersInternal() due to lack of an EOF (End of File) check might cause huge CPU consumption. When a crafted PSD file, which claims a large \"length\" field in the header but does not contain sufficient backing data, is provided, the loop over \"length\" would consume huge CPU resources, since there is no EOF check inside the loop.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:7.0.7-0:*:*:*:*:*:*:*", "matchCriteriaId": "ACD6A151-47EB-4305-B4CB-F9003BC2E5DE", "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:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"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": "In coders/psd.c in ImageMagick 7.0.7-0 Q16, a DoS in ReadPSDLayersInternal() due to lack of an EOF (End of File) check might cause huge CPU consumption. When a crafted PSD file, which claims a large \"length\" field in the header but does not contain sufficient backing data, is provided, the loop over \"length\" would consume huge CPU resources, since there is no EOF check inside the loop."}, {"lang": "es", "value": "En coders/psd.c en ImageMagick 7.0.7-0 Q16, una denegaci\u00f3n de servicio en ReadPSDLayersInternal() por una falta de chequeos EOF (End of File) podr\u00eda provocar un enorme consumo de recursos de la CPU. Cuando se proporciona un archivo PSD manipulado que pide un campo \"length\" grande en la cabecera pero no contiene suficientes datos de respaldo, el bucle en \"length\" consumir\u00eda una gran cantidad de recursos de CPU, ya que el bucle no contiene ning\u00fan chequeo EOF."}], "evaluatorComment": null, "id": "CVE-2017-14174", "lastModified": "2020-10-23T18:16:50.530", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2017-09-07T06:29:00.390", "references": [{"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/04a567494786d5bb50894fc8bb8fea0cf496bea8"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/f68a98a9d385838a1c73ec960a14102949940a64"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/issues/714"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2019/05/msg00015.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2020/09/msg00007.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201711-07"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3681-1/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-834"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/04a567494786d5bb50894fc8bb8fea0cf496bea8"}, "type": "CWE-834"}
| 310
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging",
"from contextlib import ExitStack\nfrom dateutil import parser\nfrom functools import wraps\nimport socket\nimport ipaddress\nfrom urllib.parse import urlparse",
"from six import text_type\nfrom sshtunnel import open_tunnel\nfrom redash import settings, utils\nfrom redash.utils import json_loads, query_is_select_no_limit, add_limit_to_query\nfrom rq.timeouts import JobTimeoutException\n",
"from redash.utils.requests_session import requests, requests_session",
"\nlogger = logging.getLogger(__name__)",
"__all__ = [\n \"BaseQueryRunner\",\n \"BaseHTTPQueryRunner\",\n \"InterruptException\",\n \"JobTimeoutException\",\n \"BaseSQLQueryRunner\",\n \"TYPE_DATETIME\",\n \"TYPE_BOOLEAN\",\n \"TYPE_INTEGER\",\n \"TYPE_STRING\",\n \"TYPE_DATE\",\n \"TYPE_FLOAT\",\n \"SUPPORTED_COLUMN_TYPES\",\n \"register\",\n \"get_query_runner\",\n \"import_query_runners\",\n \"guess_type\",\n]",
"# Valid types of columns returned in results:\nTYPE_INTEGER = \"integer\"\nTYPE_FLOAT = \"float\"\nTYPE_BOOLEAN = \"boolean\"\nTYPE_STRING = \"string\"\nTYPE_DATETIME = \"datetime\"\nTYPE_DATE = \"date\"",
"SUPPORTED_COLUMN_TYPES = set(\n [TYPE_INTEGER, TYPE_FLOAT, TYPE_BOOLEAN, TYPE_STRING, TYPE_DATETIME, TYPE_DATE]\n)",
"\nclass InterruptException(Exception):\n pass",
"\nclass NotSupported(Exception):\n pass",
"\nclass BaseQueryRunner(object):\n deprecated = False\n should_annotate_query = True\n noop_query = None",
" def __init__(self, configuration):\n self.syntax = \"sql\"\n self.configuration = configuration",
" @classmethod\n def name(cls):\n return cls.__name__",
" @classmethod\n def type(cls):\n return cls.__name__.lower()",
" @classmethod\n def enabled(cls):\n return True",
" @property\n def host(self):\n \"\"\"Returns this query runner's configured host.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"host\" in self.configuration:\n return self.configuration[\"host\"]\n else:\n raise NotImplementedError()",
" @host.setter\n def host(self, host):\n \"\"\"Sets this query runner's configured host.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"host\" in self.configuration:\n self.configuration[\"host\"] = host\n else:\n raise NotImplementedError()",
" @property\n def port(self):\n \"\"\"Returns this query runner's configured port.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"port\" in self.configuration:\n return self.configuration[\"port\"]\n else:\n raise NotImplementedError()",
" @port.setter\n def port(self, port):\n \"\"\"Sets this query runner's configured port.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"port\" in self.configuration:\n self.configuration[\"port\"] = port\n else:\n raise NotImplementedError()",
" @classmethod\n def configuration_schema(cls):\n return {}",
" def annotate_query(self, query, metadata):\n if not self.should_annotate_query:\n return query",
" annotation = \", \".join([\"{}: {}\".format(k, v) for k, v in metadata.items()])\n annotated_query = \"/* {} */ {}\".format(annotation, query)\n return annotated_query",
" def test_connection(self):\n if self.noop_query is None:\n raise NotImplementedError()\n data, error = self.run_query(self.noop_query, None)",
" if error is not None:\n raise Exception(error)",
" def run_query(self, query, user):\n raise NotImplementedError()",
" def fetch_columns(self, columns):\n column_names = []\n duplicates_counter = 1\n new_columns = []",
" for col in columns:\n column_name = col[0]\n if column_name in column_names:\n column_name = \"{}{}\".format(column_name, duplicates_counter)\n duplicates_counter += 1",
" column_names.append(column_name)\n new_columns.append(\n {\"name\": column_name, \"friendly_name\": column_name, \"type\": col[1]}\n )",
" return new_columns",
" def get_schema(self, get_stats=False):\n raise NotSupported()",
" def _run_query_internal(self, query):\n results, error = self.run_query(query, None)",
" if error is not None:\n raise Exception(\"Failed running query [%s].\" % query)\n return json_loads(results)[\"rows\"]",
" @classmethod\n def to_dict(cls):\n return {\n \"name\": cls.name(),\n \"type\": cls.type(),\n \"configuration_schema\": cls.configuration_schema(),\n **({\"deprecated\": True} if cls.deprecated else {}),\n }",
" @property\n def supports_auto_limit(self):\n return False",
" def apply_auto_limit(self, query_text, should_apply_auto_limit):\n return query_text",
" def gen_query_hash(self, query_text, set_auto_limit=False):\n query_text = self.apply_auto_limit(query_text, set_auto_limit)\n return utils.gen_query_hash(query_text)",
"\nclass BaseSQLQueryRunner(BaseQueryRunner):\n def get_schema(self, get_stats=False):\n schema_dict = {}\n self._get_tables(schema_dict)\n if settings.SCHEMA_RUN_TABLE_SIZE_CALCULATIONS and get_stats:\n self._get_tables_stats(schema_dict)\n return list(schema_dict.values())",
" def _get_tables(self, schema_dict):\n return []",
" def _get_tables_stats(self, tables_dict):\n for t in tables_dict.keys():\n if type(tables_dict[t]) == dict:\n res = self._run_query_internal(\"select count(*) as cnt from %s\" % t)\n tables_dict[t][\"size\"] = res[0][\"cnt\"]",
" @property\n def supports_auto_limit(self):\n return True",
" def apply_auto_limit(self, query_text, should_apply_auto_limit):\n if should_apply_auto_limit:\n from redash.query_runner.databricks import split_sql_statements, combine_sql_statements\n queries = split_sql_statements(query_text)\n # we only check for last one in the list because it is the one that we show result\n last_query = queries[-1]\n if query_is_select_no_limit(last_query):\n queries[-1] = add_limit_to_query(last_query)\n return combine_sql_statements(queries)\n else:\n return query_text",
"",
"def is_private_address(url):\n hostname = urlparse(url).hostname\n ip_address = socket.gethostbyname(hostname)\n return ipaddress.ip_address(text_type(ip_address)).is_private",
"",
"class BaseHTTPQueryRunner(BaseQueryRunner):\n should_annotate_query = False\n response_error = \"Endpoint returned unexpected status code\"\n requires_authentication = False\n requires_url = True\n url_title = \"URL base path\"\n username_title = \"HTTP Basic Auth Username\"\n password_title = \"HTTP Basic Auth Password\"",
" @classmethod\n def configuration_schema(cls):\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"url\": {\"type\": \"string\", \"title\": cls.url_title},\n \"username\": {\"type\": \"string\", \"title\": cls.username_title},\n \"password\": {\"type\": \"string\", \"title\": cls.password_title},\n },\n \"secret\": [\"password\"],\n \"order\": [\"url\", \"username\", \"password\"],\n }",
" if cls.requires_url or cls.requires_authentication:\n schema[\"required\"] = []",
" if cls.requires_url:\n schema[\"required\"] += [\"url\"]",
" if cls.requires_authentication:\n schema[\"required\"] += [\"username\", \"password\"]\n return schema",
" def get_auth(self):\n username = self.configuration.get(\"username\")\n password = self.configuration.get(\"password\")\n if username and password:\n return (username, password)\n if self.requires_authentication:\n raise ValueError(\"Username and Password required\")\n else:\n return None",
" def get_response(self, url, auth=None, http_method=\"get\", **kwargs):",
" if is_private_address(url) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:\n raise Exception(\"Can't query private addresses.\")",
"\n # Get authentication values if not given\n if auth is None:\n auth = self.get_auth()",
" # Then call requests to get the response from the given endpoint\n # URL optionally, with the additional requests parameters.\n error = None\n response = None\n try:\n response = requests_session.request(http_method, url, auth=auth, **kwargs)\n # Raise a requests HTTP exception with the appropriate reason\n # for 4xx and 5xx response status codes which is later caught\n # and passed back.\n response.raise_for_status()",
" # Any other responses (e.g. 2xx and 3xx):\n if response.status_code != 200:\n error = \"{} ({}).\".format(self.response_error, response.status_code)\n",
" except requests.HTTPError as exc:",
" logger.exception(exc)\n error = \"Failed to execute query. \" \"Return Code: {} Reason: {}\".format(\n response.status_code, response.text\n )",
" except requests.RequestException as exc:",
" # Catch all other requests exceptions and return the error.\n logger.exception(exc)\n error = str(exc)",
" # Return response and error.\n return response, error",
"\nquery_runners = {}",
"\ndef register(query_runner_class):\n global query_runners\n if query_runner_class.enabled():\n logger.debug(\n \"Registering %s (%s) query runner.\",\n query_runner_class.name(),\n query_runner_class.type(),\n )\n query_runners[query_runner_class.type()] = query_runner_class\n else:\n logger.debug(\n \"%s query runner enabled but not supported, not registering. Either disable or install missing \"\n \"dependencies.\",\n query_runner_class.name(),\n )",
"\ndef get_query_runner(query_runner_type, configuration):\n query_runner_class = query_runners.get(query_runner_type, None)\n if query_runner_class is None:\n return None",
" return query_runner_class(configuration)",
"\ndef get_configuration_schema_for_query_runner_type(query_runner_type):\n query_runner_class = query_runners.get(query_runner_type, None)\n if query_runner_class is None:\n return None",
" return query_runner_class.configuration_schema()",
"\ndef import_query_runners(query_runner_imports):\n for runner_import in query_runner_imports:\n __import__(runner_import)",
"\ndef guess_type(value):\n if isinstance(value, bool):\n return TYPE_BOOLEAN\n elif isinstance(value, int):\n return TYPE_INTEGER\n elif isinstance(value, float):\n return TYPE_FLOAT",
" return guess_type_from_string(value)",
"\ndef guess_type_from_string(string_value):\n if string_value == \"\" or string_value is None:\n return TYPE_STRING",
" try:\n int(string_value)\n return TYPE_INTEGER\n except (ValueError, OverflowError):\n pass",
" try:\n float(string_value)\n return TYPE_FLOAT\n except (ValueError, OverflowError):\n pass",
" if str(string_value).lower() in (\"true\", \"false\"):\n return TYPE_BOOLEAN",
" try:\n parser.parse(string_value)\n return TYPE_DATETIME\n except (ValueError, OverflowError):\n pass",
" return TYPE_STRING",
"\ndef with_ssh_tunnel(query_runner, details):\n def tunnel(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n try:\n remote_host, remote_port = query_runner.host, query_runner.port\n except NotImplementedError:\n raise NotImplementedError(\n \"SSH tunneling is not implemented for this query runner yet.\"\n )",
" stack = ExitStack()\n try:\n bastion_address = (details[\"ssh_host\"], details.get(\"ssh_port\", 22))\n remote_address = (remote_host, remote_port)\n auth = {\n \"ssh_username\": details[\"ssh_username\"],\n **settings.dynamic_settings.ssh_tunnel_auth(),\n }\n server = stack.enter_context(\n open_tunnel(\n bastion_address, remote_bind_address=remote_address, **auth\n )\n )\n except Exception as error:\n raise type(error)(\"SSH tunnel: {}\".format(str(error)))",
" with stack:\n try:\n query_runner.host, query_runner.port = server.local_bind_address\n result = f(*args, **kwargs)\n finally:\n query_runner.host, query_runner.port = remote_host, remote_port",
" return result",
" return wrapper",
" query_runner.run_query = tunnel(query_runner.run_query)",
" return query_runner"
] |
[
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,
0,
0,
1,
1,
1,
1,
1,
1,
1,
0,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging",
"from contextlib import ExitStack\nfrom dateutil import parser\nfrom functools import wraps\nimport socket\nimport ipaddress\nfrom urllib.parse import urlparse",
"from six import text_type\nfrom sshtunnel import open_tunnel\nfrom redash import settings, utils\nfrom redash.utils import json_loads, query_is_select_no_limit, add_limit_to_query\nfrom rq.timeouts import JobTimeoutException\n",
"from redash.utils.requests_session import requests_or_advocate, requests_session, UnacceptableAddressException\n",
"\nlogger = logging.getLogger(__name__)",
"__all__ = [\n \"BaseQueryRunner\",\n \"BaseHTTPQueryRunner\",\n \"InterruptException\",\n \"JobTimeoutException\",\n \"BaseSQLQueryRunner\",\n \"TYPE_DATETIME\",\n \"TYPE_BOOLEAN\",\n \"TYPE_INTEGER\",\n \"TYPE_STRING\",\n \"TYPE_DATE\",\n \"TYPE_FLOAT\",\n \"SUPPORTED_COLUMN_TYPES\",\n \"register\",\n \"get_query_runner\",\n \"import_query_runners\",\n \"guess_type\",\n]",
"# Valid types of columns returned in results:\nTYPE_INTEGER = \"integer\"\nTYPE_FLOAT = \"float\"\nTYPE_BOOLEAN = \"boolean\"\nTYPE_STRING = \"string\"\nTYPE_DATETIME = \"datetime\"\nTYPE_DATE = \"date\"",
"SUPPORTED_COLUMN_TYPES = set(\n [TYPE_INTEGER, TYPE_FLOAT, TYPE_BOOLEAN, TYPE_STRING, TYPE_DATETIME, TYPE_DATE]\n)",
"\nclass InterruptException(Exception):\n pass",
"\nclass NotSupported(Exception):\n pass",
"\nclass BaseQueryRunner(object):\n deprecated = False\n should_annotate_query = True\n noop_query = None",
" def __init__(self, configuration):\n self.syntax = \"sql\"\n self.configuration = configuration",
" @classmethod\n def name(cls):\n return cls.__name__",
" @classmethod\n def type(cls):\n return cls.__name__.lower()",
" @classmethod\n def enabled(cls):\n return True",
" @property\n def host(self):\n \"\"\"Returns this query runner's configured host.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"host\" in self.configuration:\n return self.configuration[\"host\"]\n else:\n raise NotImplementedError()",
" @host.setter\n def host(self, host):\n \"\"\"Sets this query runner's configured host.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"host\" in self.configuration:\n self.configuration[\"host\"] = host\n else:\n raise NotImplementedError()",
" @property\n def port(self):\n \"\"\"Returns this query runner's configured port.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"port\" in self.configuration:\n return self.configuration[\"port\"]\n else:\n raise NotImplementedError()",
" @port.setter\n def port(self, port):\n \"\"\"Sets this query runner's configured port.\n This is used primarily for temporarily swapping endpoints when using SSH tunnels to connect to a data source.",
" `BaseQueryRunner`'s naïve implementation supports query runner implementations that store endpoints using `host` and `port`\n configuration values. If your query runner uses a different schema (e.g. a web address), you should override this function.\n \"\"\"\n if \"port\" in self.configuration:\n self.configuration[\"port\"] = port\n else:\n raise NotImplementedError()",
" @classmethod\n def configuration_schema(cls):\n return {}",
" def annotate_query(self, query, metadata):\n if not self.should_annotate_query:\n return query",
" annotation = \", \".join([\"{}: {}\".format(k, v) for k, v in metadata.items()])\n annotated_query = \"/* {} */ {}\".format(annotation, query)\n return annotated_query",
" def test_connection(self):\n if self.noop_query is None:\n raise NotImplementedError()\n data, error = self.run_query(self.noop_query, None)",
" if error is not None:\n raise Exception(error)",
" def run_query(self, query, user):\n raise NotImplementedError()",
" def fetch_columns(self, columns):\n column_names = []\n duplicates_counter = 1\n new_columns = []",
" for col in columns:\n column_name = col[0]\n if column_name in column_names:\n column_name = \"{}{}\".format(column_name, duplicates_counter)\n duplicates_counter += 1",
" column_names.append(column_name)\n new_columns.append(\n {\"name\": column_name, \"friendly_name\": column_name, \"type\": col[1]}\n )",
" return new_columns",
" def get_schema(self, get_stats=False):\n raise NotSupported()",
" def _run_query_internal(self, query):\n results, error = self.run_query(query, None)",
" if error is not None:\n raise Exception(\"Failed running query [%s].\" % query)\n return json_loads(results)[\"rows\"]",
" @classmethod\n def to_dict(cls):\n return {\n \"name\": cls.name(),\n \"type\": cls.type(),\n \"configuration_schema\": cls.configuration_schema(),\n **({\"deprecated\": True} if cls.deprecated else {}),\n }",
" @property\n def supports_auto_limit(self):\n return False",
" def apply_auto_limit(self, query_text, should_apply_auto_limit):\n return query_text",
" def gen_query_hash(self, query_text, set_auto_limit=False):\n query_text = self.apply_auto_limit(query_text, set_auto_limit)\n return utils.gen_query_hash(query_text)",
"\nclass BaseSQLQueryRunner(BaseQueryRunner):\n def get_schema(self, get_stats=False):\n schema_dict = {}\n self._get_tables(schema_dict)\n if settings.SCHEMA_RUN_TABLE_SIZE_CALCULATIONS and get_stats:\n self._get_tables_stats(schema_dict)\n return list(schema_dict.values())",
" def _get_tables(self, schema_dict):\n return []",
" def _get_tables_stats(self, tables_dict):\n for t in tables_dict.keys():\n if type(tables_dict[t]) == dict:\n res = self._run_query_internal(\"select count(*) as cnt from %s\" % t)\n tables_dict[t][\"size\"] = res[0][\"cnt\"]",
" @property\n def supports_auto_limit(self):\n return True",
" def apply_auto_limit(self, query_text, should_apply_auto_limit):\n if should_apply_auto_limit:\n from redash.query_runner.databricks import split_sql_statements, combine_sql_statements\n queries = split_sql_statements(query_text)\n # we only check for last one in the list because it is the one that we show result\n last_query = queries[-1]\n if query_is_select_no_limit(last_query):\n queries[-1] = add_limit_to_query(last_query)\n return combine_sql_statements(queries)\n else:\n return query_text",
"",
"",
"class BaseHTTPQueryRunner(BaseQueryRunner):\n should_annotate_query = False\n response_error = \"Endpoint returned unexpected status code\"\n requires_authentication = False\n requires_url = True\n url_title = \"URL base path\"\n username_title = \"HTTP Basic Auth Username\"\n password_title = \"HTTP Basic Auth Password\"",
" @classmethod\n def configuration_schema(cls):\n schema = {\n \"type\": \"object\",\n \"properties\": {\n \"url\": {\"type\": \"string\", \"title\": cls.url_title},\n \"username\": {\"type\": \"string\", \"title\": cls.username_title},\n \"password\": {\"type\": \"string\", \"title\": cls.password_title},\n },\n \"secret\": [\"password\"],\n \"order\": [\"url\", \"username\", \"password\"],\n }",
" if cls.requires_url or cls.requires_authentication:\n schema[\"required\"] = []",
" if cls.requires_url:\n schema[\"required\"] += [\"url\"]",
" if cls.requires_authentication:\n schema[\"required\"] += [\"username\", \"password\"]\n return schema",
" def get_auth(self):\n username = self.configuration.get(\"username\")\n password = self.configuration.get(\"password\")\n if username and password:\n return (username, password)\n if self.requires_authentication:\n raise ValueError(\"Username and Password required\")\n else:\n return None",
" def get_response(self, url, auth=None, http_method=\"get\", **kwargs):",
"",
"\n # Get authentication values if not given\n if auth is None:\n auth = self.get_auth()",
" # Then call requests to get the response from the given endpoint\n # URL optionally, with the additional requests parameters.\n error = None\n response = None\n try:\n response = requests_session.request(http_method, url, auth=auth, **kwargs)\n # Raise a requests HTTP exception with the appropriate reason\n # for 4xx and 5xx response status codes which is later caught\n # and passed back.\n response.raise_for_status()",
" # Any other responses (e.g. 2xx and 3xx):\n if response.status_code != 200:\n error = \"{} ({}).\".format(self.response_error, response.status_code)\n",
" except requests_or_advocate.HTTPError as exc:",
" logger.exception(exc)\n error = \"Failed to execute query. \" \"Return Code: {} Reason: {}\".format(\n response.status_code, response.text\n )",
" except UnacceptableAddressException as exc:\n logger.exception(exc)\n error = \"Can't query private addresses.\"\n except requests_or_advocate.RequestException as exc:",
" # Catch all other requests exceptions and return the error.\n logger.exception(exc)\n error = str(exc)",
" # Return response and error.\n return response, error",
"\nquery_runners = {}",
"\ndef register(query_runner_class):\n global query_runners\n if query_runner_class.enabled():\n logger.debug(\n \"Registering %s (%s) query runner.\",\n query_runner_class.name(),\n query_runner_class.type(),\n )\n query_runners[query_runner_class.type()] = query_runner_class\n else:\n logger.debug(\n \"%s query runner enabled but not supported, not registering. Either disable or install missing \"\n \"dependencies.\",\n query_runner_class.name(),\n )",
"\ndef get_query_runner(query_runner_type, configuration):\n query_runner_class = query_runners.get(query_runner_type, None)\n if query_runner_class is None:\n return None",
" return query_runner_class(configuration)",
"\ndef get_configuration_schema_for_query_runner_type(query_runner_type):\n query_runner_class = query_runners.get(query_runner_type, None)\n if query_runner_class is None:\n return None",
" return query_runner_class.configuration_schema()",
"\ndef import_query_runners(query_runner_imports):\n for runner_import in query_runner_imports:\n __import__(runner_import)",
"\ndef guess_type(value):\n if isinstance(value, bool):\n return TYPE_BOOLEAN\n elif isinstance(value, int):\n return TYPE_INTEGER\n elif isinstance(value, float):\n return TYPE_FLOAT",
" return guess_type_from_string(value)",
"\ndef guess_type_from_string(string_value):\n if string_value == \"\" or string_value is None:\n return TYPE_STRING",
" try:\n int(string_value)\n return TYPE_INTEGER\n except (ValueError, OverflowError):\n pass",
" try:\n float(string_value)\n return TYPE_FLOAT\n except (ValueError, OverflowError):\n pass",
" if str(string_value).lower() in (\"true\", \"false\"):\n return TYPE_BOOLEAN",
" try:\n parser.parse(string_value)\n return TYPE_DATETIME\n except (ValueError, OverflowError):\n pass",
" return TYPE_STRING",
"\ndef with_ssh_tunnel(query_runner, details):\n def tunnel(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n try:\n remote_host, remote_port = query_runner.host, query_runner.port\n except NotImplementedError:\n raise NotImplementedError(\n \"SSH tunneling is not implemented for this query runner yet.\"\n )",
" stack = ExitStack()\n try:\n bastion_address = (details[\"ssh_host\"], details.get(\"ssh_port\", 22))\n remote_address = (remote_host, remote_port)\n auth = {\n \"ssh_username\": details[\"ssh_username\"],\n **settings.dynamic_settings.ssh_tunnel_auth(),\n }\n server = stack.enter_context(\n open_tunnel(\n bastion_address, remote_bind_address=remote_address, **auth\n )\n )\n except Exception as error:\n raise type(error)(\"SSH tunnel: {}\".format(str(error)))",
" with stack:\n try:\n query_runner.host, query_runner.port = server.local_bind_address\n result = f(*args, **kwargs)\n finally:\n query_runner.host, query_runner.port = remote_host, remote_port",
" return result",
" return wrapper",
" query_runner.run_query = tunnel(query_runner.run_query)",
" return query_runner"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging\nimport yaml",
"import requests",
"import io\n",
"from redash import settings",
"from redash.query_runner import *\nfrom redash.utils import json_dumps",
"logger = logging.getLogger(__name__)",
"try:\n import pandas as pd\n import numpy as np\n enabled = True\nexcept ImportError:\n enabled = False",
"\nclass CSV(BaseQueryRunner):\n should_annotate_query = False",
" @classmethod\n def name(cls):\n return \"CSV\"",
" @classmethod\n def enabled(cls):\n return enabled",
" @classmethod\n def configuration_schema(cls):\n return {\n 'type': 'object',\n 'properties': {},\n }",
" def __init__(self, configuration):\n super(CSV, self).__init__(configuration)\n self.syntax = \"yaml\"",
" def test_connection(self):\n pass",
" def run_query(self, query, user):\n path = \"\"\n ua = \"\"\n args = {}\n try:\n args = yaml.safe_load(query)\n path = args['url']\n args.pop('url', None)\n ua = args['user-agent']\n args.pop('user-agent', None)",
"\n if is_private_address(path) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:\n raise Exception(\"Can't query private addresses.\")",
" except:\n pass",
" try:",
" response = requests.get(url=path, headers={\"User-agent\": ua})",
" workbook = pd.read_csv(io.BytesIO(response.content),sep=\",\", **args)",
" df = workbook.copy()\n data = {'columns': [], 'rows': []}\n conversions = [\n {'pandas_type': np.integer, 'redash_type': 'integer',},\n {'pandas_type': np.inexact, 'redash_type': 'float',},\n {'pandas_type': np.datetime64, 'redash_type': 'datetime', 'to_redash': lambda x: x.strftime('%Y-%m-%d %H:%M:%S')},\n {'pandas_type': np.bool_, 'redash_type': 'boolean'},\n {'pandas_type': np.object, 'redash_type': 'string'}\n ]\n labels = []\n for dtype, label in zip(df.dtypes, df.columns):\n for conversion in conversions:\n if issubclass(dtype.type, conversion['pandas_type']):\n data['columns'].append({'name': label, 'friendly_name': label, 'type': conversion['redash_type']})\n labels.append(label)\n func = conversion.get('to_redash')\n if func:\n df[label] = df[label].apply(func)\n break\n data['rows'] = df[labels].replace({np.nan: None}).to_dict(orient='records')",
" json_data = json_dumps(data)\n error = None\n except KeyboardInterrupt:\n error = \"Query cancelled by user.\"\n json_data = None",
"",
" except Exception as e:\n error = \"Error reading {0}. {1}\".format(path, str(e))\n json_data = None",
" return json_data, error",
" def get_schema(self):\n raise NotSupported()",
"register(CSV)"
] |
[
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging\nimport yaml",
"",
"import io\n",
"from redash.utils.requests_session import requests_or_advocate, UnacceptableAddressException\n",
"from redash.query_runner import *\nfrom redash.utils import json_dumps",
"logger = logging.getLogger(__name__)",
"try:\n import pandas as pd\n import numpy as np\n enabled = True\nexcept ImportError:\n enabled = False",
"\nclass CSV(BaseQueryRunner):\n should_annotate_query = False",
" @classmethod\n def name(cls):\n return \"CSV\"",
" @classmethod\n def enabled(cls):\n return enabled",
" @classmethod\n def configuration_schema(cls):\n return {\n 'type': 'object',\n 'properties': {},\n }",
" def __init__(self, configuration):\n super(CSV, self).__init__(configuration)\n self.syntax = \"yaml\"",
" def test_connection(self):\n pass",
" def run_query(self, query, user):\n path = \"\"\n ua = \"\"\n args = {}\n try:\n args = yaml.safe_load(query)\n path = args['url']\n args.pop('url', None)\n ua = args['user-agent']\n args.pop('user-agent', None)",
"",
" except:\n pass",
" try:",
" response = requests_or_advocate.get(url=path, headers={\"User-agent\": ua})",
" workbook = pd.read_csv(io.BytesIO(response.content),sep=\",\", **args)",
" df = workbook.copy()\n data = {'columns': [], 'rows': []}\n conversions = [\n {'pandas_type': np.integer, 'redash_type': 'integer',},\n {'pandas_type': np.inexact, 'redash_type': 'float',},\n {'pandas_type': np.datetime64, 'redash_type': 'datetime', 'to_redash': lambda x: x.strftime('%Y-%m-%d %H:%M:%S')},\n {'pandas_type': np.bool_, 'redash_type': 'boolean'},\n {'pandas_type': np.object, 'redash_type': 'string'}\n ]\n labels = []\n for dtype, label in zip(df.dtypes, df.columns):\n for conversion in conversions:\n if issubclass(dtype.type, conversion['pandas_type']):\n data['columns'].append({'name': label, 'friendly_name': label, 'type': conversion['redash_type']})\n labels.append(label)\n func = conversion.get('to_redash')\n if func:\n df[label] = df[label].apply(func)\n break\n data['rows'] = df[labels].replace({np.nan: None}).to_dict(orient='records')",
" json_data = json_dumps(data)\n error = None\n except KeyboardInterrupt:\n error = \"Query cancelled by user.\"\n json_data = None",
" except UnacceptableAddressException:\n error = \"Can't query private addresses.\"\n json_data = None",
" except Exception as e:\n error = \"Error reading {0}. {1}\".format(path, str(e))\n json_data = None",
" return json_data, error",
" def get_schema(self):\n raise NotSupported()",
"register(CSV)"
] |
[
1,
1,
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": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging\nimport yaml",
"import requests",
"",
"from redash import settings",
"from redash.query_runner import *\nfrom redash.utils import json_dumps",
"logger = logging.getLogger(__name__)",
"try:\n import pandas as pd\n import xlrd\n import openpyxl\n import numpy as np\n enabled = True\nexcept ImportError:\n enabled = False",
"class Excel(BaseQueryRunner):\n should_annotate_query = False",
" @classmethod\n def enabled(cls):\n return enabled",
" @classmethod\n def configuration_schema(cls):\n return {\n 'type': 'object',\n 'properties': {},\n }",
" def __init__(self, configuration):\n super(Excel, self).__init__(configuration)\n self.syntax = \"yaml\"",
" def test_connection(self):\n pass",
" def run_query(self, query, user):\n path = \"\"\n ua = \"\"\n args = {}\n try:\n args = yaml.safe_load(query)\n path = args['url']\n args.pop('url', None)\n ua = args['user-agent']\n args.pop('user-agent', None)\n",
" if is_private_address(path) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:\n raise Exception(\"Can't query private addresses.\")",
" except:\n pass",
" try:",
" response = requests.get(url=path, headers={\"User-agent\": ua})",
" workbook = pd.read_excel(response.content, **args)",
" df = workbook.copy()\n data = {'columns': [], 'rows': []}\n conversions = [\n {'pandas_type': np.integer, 'redash_type': 'integer',},\n {'pandas_type': np.inexact, 'redash_type': 'float',},\n {'pandas_type': np.datetime64, 'redash_type': 'datetime', 'to_redash': lambda x: x.strftime('%Y-%m-%d %H:%M:%S')},\n {'pandas_type': np.bool_, 'redash_type': 'boolean'},\n {'pandas_type': np.object, 'redash_type': 'string'}\n ]\n labels = []\n for dtype, label in zip(df.dtypes, df.columns):\n for conversion in conversions:\n if issubclass(dtype.type, conversion['pandas_type']):\n data['columns'].append({'name': label, 'friendly_name': label, 'type': conversion['redash_type']})\n labels.append(label)\n func = conversion.get('to_redash')\n if func:\n df[label] = df[label].apply(func)\n break\n data['rows'] = df[labels].replace({np.nan: None}).to_dict(orient='records')",
" json_data = json_dumps(data)\n error = None\n except KeyboardInterrupt:\n error = \"Query cancelled by user.\"\n json_data = None",
"",
" except Exception as e:\n error = \"Error reading {0}. {1}\".format(path, str(e))\n json_data = None",
" return json_data, error",
" def get_schema(self):\n raise NotSupported()",
"register(Excel)"
] |
[
1,
0,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging\nimport yaml",
"",
"",
"from redash.utils.requests_session import requests_or_advocate, UnacceptableAddressException\n",
"from redash.query_runner import *\nfrom redash.utils import json_dumps",
"logger = logging.getLogger(__name__)",
"try:\n import pandas as pd\n import xlrd\n import openpyxl\n import numpy as np\n enabled = True\nexcept ImportError:\n enabled = False",
"class Excel(BaseQueryRunner):\n should_annotate_query = False",
" @classmethod\n def enabled(cls):\n return enabled",
" @classmethod\n def configuration_schema(cls):\n return {\n 'type': 'object',\n 'properties': {},\n }",
" def __init__(self, configuration):\n super(Excel, self).__init__(configuration)\n self.syntax = \"yaml\"",
" def test_connection(self):\n pass",
" def run_query(self, query, user):\n path = \"\"\n ua = \"\"\n args = {}\n try:\n args = yaml.safe_load(query)\n path = args['url']\n args.pop('url', None)\n ua = args['user-agent']\n args.pop('user-agent', None)\n",
"",
" except:\n pass",
" try:",
" response = requests_or_advocate.get(url=path, headers={\"User-agent\": ua})",
" workbook = pd.read_excel(response.content, **args)",
" df = workbook.copy()\n data = {'columns': [], 'rows': []}\n conversions = [\n {'pandas_type': np.integer, 'redash_type': 'integer',},\n {'pandas_type': np.inexact, 'redash_type': 'float',},\n {'pandas_type': np.datetime64, 'redash_type': 'datetime', 'to_redash': lambda x: x.strftime('%Y-%m-%d %H:%M:%S')},\n {'pandas_type': np.bool_, 'redash_type': 'boolean'},\n {'pandas_type': np.object, 'redash_type': 'string'}\n ]\n labels = []\n for dtype, label in zip(df.dtypes, df.columns):\n for conversion in conversions:\n if issubclass(dtype.type, conversion['pandas_type']):\n data['columns'].append({'name': label, 'friendly_name': label, 'type': conversion['redash_type']})\n labels.append(label)\n func = conversion.get('to_redash')\n if func:\n df[label] = df[label].apply(func)\n break\n data['rows'] = df[labels].replace({np.nan: None}).to_dict(orient='records')",
" json_data = json_dumps(data)\n error = None\n except KeyboardInterrupt:\n error = \"Query cancelled by user.\"\n json_data = None",
" except UnacceptableAddressException:\n error = \"Can't query private addresses.\"\n json_data = None",
" except Exception as e:\n error = \"Error reading {0}. {1}\".format(path, str(e))\n json_data = None",
" return json_data, error",
" def get_schema(self):\n raise NotSupported()",
"register(Excel)"
] |
[
1,
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": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging\nimport yaml\nimport datetime\nfrom funcy import compact, project",
"from redash import settings",
"from redash.utils import json_dumps\nfrom redash.query_runner import (\n BaseHTTPQueryRunner,\n register,\n TYPE_BOOLEAN,\n TYPE_DATETIME,\n TYPE_FLOAT,\n TYPE_INTEGER,\n TYPE_STRING,",
" is_private_address,",
")",
"\nclass QueryParseError(Exception):\n pass",
"\ndef parse_query(query):\n # TODO: copy paste from Metrica query runner, we should extract this into a utility\n query = query.strip()\n if query == \"\":\n raise QueryParseError(\"Query is empty.\")\n try:\n params = yaml.safe_load(query)\n return params\n except ValueError as e:\n logging.exception(e)\n error = str(e)\n raise QueryParseError(error)",
"\nTYPES_MAP = {\n str: TYPE_STRING,\n bytes: TYPE_STRING,\n int: TYPE_INTEGER,\n float: TYPE_FLOAT,\n bool: TYPE_BOOLEAN,\n datetime.datetime: TYPE_DATETIME,\n}",
"\ndef _get_column_by_name(columns, column_name):\n for c in columns:\n if \"name\" in c and c[\"name\"] == column_name:\n return c",
" return None",
"\ndef _get_type(value):\n return TYPES_MAP.get(type(value), TYPE_STRING)",
"\ndef add_column(columns, column_name, column_type):\n if _get_column_by_name(columns, column_name) is None:\n columns.append(\n {\"name\": column_name, \"friendly_name\": column_name, \"type\": column_type}\n )",
"\ndef _apply_path_search(response, path):\n if path is None:\n return response",
" path_parts = path.split(\".\")\n path_parts.reverse()\n while len(path_parts) > 0:\n current_path = path_parts.pop()\n if current_path in response:\n response = response[current_path]\n else:\n raise Exception(\"Couldn't find path {} in response.\".format(path))",
" return response",
"\ndef _normalize_json(data, path):\n data = _apply_path_search(data, path)",
" if isinstance(data, dict):\n data = [data]",
" return data",
"\ndef _sort_columns_with_fields(columns, fields):\n if fields:\n columns = compact([_get_column_by_name(columns, field) for field in fields])",
" return columns",
"\n# TODO: merge the logic here with the one in MongoDB's queyr runner\ndef parse_json(data, path, fields):\n data = _normalize_json(data, path)",
" rows = []\n columns = []",
" for row in data:\n parsed_row = {}",
" for key in row:\n if isinstance(row[key], dict):\n for inner_key in row[key]:\n column_name = \"{}.{}\".format(key, inner_key)\n if fields and key not in fields and column_name not in fields:\n continue",
" value = row[key][inner_key]\n add_column(columns, column_name, _get_type(value))\n parsed_row[column_name] = value\n else:\n if fields and key not in fields:\n continue",
" value = row[key]\n add_column(columns, key, _get_type(value))\n parsed_row[key] = row[key]",
" rows.append(parsed_row)",
" columns = _sort_columns_with_fields(columns, fields)",
" return {\"rows\": rows, \"columns\": columns}",
"\nclass JSON(BaseHTTPQueryRunner):\n requires_url = False",
" @classmethod\n def configuration_schema(cls):\n return {\n \"type\": \"object\",\n \"properties\": {\n \"username\": {\"type\": \"string\", \"title\": cls.username_title},\n \"password\": {\"type\": \"string\", \"title\": cls.password_title},\n },\n \"secret\": [\"password\"],\n \"order\": [\"username\", \"password\"],\n }",
" def __init__(self, configuration):\n super(JSON, self).__init__(configuration)\n self.syntax = \"yaml\"",
" def test_connection(self):\n pass",
" def run_query(self, query, user):\n query = parse_query(query)",
" if not isinstance(query, dict):\n raise QueryParseError(\n \"Query should be a YAML object describing the URL to query.\"\n )",
" if \"url\" not in query:\n raise QueryParseError(\"Query must include 'url' option.\")\n",
" if is_private_address(query[\"url\"]) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:\n raise Exception(\"Can't query private addresses.\")",
"\n method = query.get(\"method\", \"get\")\n request_options = project(query, (\"params\", \"headers\", \"data\", \"auth\", \"json\"))",
" fields = query.get(\"fields\")\n path = query.get(\"path\")",
" if isinstance(request_options.get(\"auth\", None), list):\n request_options[\"auth\"] = tuple(request_options[\"auth\"])\n elif self.configuration.get(\"username\") or self.configuration.get(\"password\"):\n request_options[\"auth\"] = (\n self.configuration.get(\"username\"),\n self.configuration.get(\"password\"),\n )",
" if method not in (\"get\", \"post\"):\n raise QueryParseError(\"Only GET or POST methods are allowed.\")",
" if fields and not isinstance(fields, list):\n raise QueryParseError(\"'fields' needs to be a list.\")",
" response, error = self.get_response(\n query[\"url\"], http_method=method, **request_options\n )",
" if error is not None:\n return None, error",
" data = json_dumps(parse_json(response.json(), path, fields))",
" if data:\n return data, None\n else:\n return None, \"Got empty response from '{}'.\".format(query[\"url\"])",
"\nregister(JSON)"
] |
[
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,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import logging\nimport yaml\nimport datetime\nfrom funcy import compact, project",
"\nfrom redash.utils.requests_session import requests_or_advocate, UnacceptableAddressException\n",
"from redash.utils import json_dumps\nfrom redash.query_runner import (\n BaseHTTPQueryRunner,\n register,\n TYPE_BOOLEAN,\n TYPE_DATETIME,\n TYPE_FLOAT,\n TYPE_INTEGER,\n TYPE_STRING,",
"",
")",
"\nclass QueryParseError(Exception):\n pass",
"\ndef parse_query(query):\n # TODO: copy paste from Metrica query runner, we should extract this into a utility\n query = query.strip()\n if query == \"\":\n raise QueryParseError(\"Query is empty.\")\n try:\n params = yaml.safe_load(query)\n return params\n except ValueError as e:\n logging.exception(e)\n error = str(e)\n raise QueryParseError(error)",
"\nTYPES_MAP = {\n str: TYPE_STRING,\n bytes: TYPE_STRING,\n int: TYPE_INTEGER,\n float: TYPE_FLOAT,\n bool: TYPE_BOOLEAN,\n datetime.datetime: TYPE_DATETIME,\n}",
"\ndef _get_column_by_name(columns, column_name):\n for c in columns:\n if \"name\" in c and c[\"name\"] == column_name:\n return c",
" return None",
"\ndef _get_type(value):\n return TYPES_MAP.get(type(value), TYPE_STRING)",
"\ndef add_column(columns, column_name, column_type):\n if _get_column_by_name(columns, column_name) is None:\n columns.append(\n {\"name\": column_name, \"friendly_name\": column_name, \"type\": column_type}\n )",
"\ndef _apply_path_search(response, path):\n if path is None:\n return response",
" path_parts = path.split(\".\")\n path_parts.reverse()\n while len(path_parts) > 0:\n current_path = path_parts.pop()\n if current_path in response:\n response = response[current_path]\n else:\n raise Exception(\"Couldn't find path {} in response.\".format(path))",
" return response",
"\ndef _normalize_json(data, path):\n data = _apply_path_search(data, path)",
" if isinstance(data, dict):\n data = [data]",
" return data",
"\ndef _sort_columns_with_fields(columns, fields):\n if fields:\n columns = compact([_get_column_by_name(columns, field) for field in fields])",
" return columns",
"\n# TODO: merge the logic here with the one in MongoDB's queyr runner\ndef parse_json(data, path, fields):\n data = _normalize_json(data, path)",
" rows = []\n columns = []",
" for row in data:\n parsed_row = {}",
" for key in row:\n if isinstance(row[key], dict):\n for inner_key in row[key]:\n column_name = \"{}.{}\".format(key, inner_key)\n if fields and key not in fields and column_name not in fields:\n continue",
" value = row[key][inner_key]\n add_column(columns, column_name, _get_type(value))\n parsed_row[column_name] = value\n else:\n if fields and key not in fields:\n continue",
" value = row[key]\n add_column(columns, key, _get_type(value))\n parsed_row[key] = row[key]",
" rows.append(parsed_row)",
" columns = _sort_columns_with_fields(columns, fields)",
" return {\"rows\": rows, \"columns\": columns}",
"\nclass JSON(BaseHTTPQueryRunner):\n requires_url = False",
" @classmethod\n def configuration_schema(cls):\n return {\n \"type\": \"object\",\n \"properties\": {\n \"username\": {\"type\": \"string\", \"title\": cls.username_title},\n \"password\": {\"type\": \"string\", \"title\": cls.password_title},\n },\n \"secret\": [\"password\"],\n \"order\": [\"username\", \"password\"],\n }",
" def __init__(self, configuration):\n super(JSON, self).__init__(configuration)\n self.syntax = \"yaml\"",
" def test_connection(self):\n pass",
" def run_query(self, query, user):\n query = parse_query(query)",
" if not isinstance(query, dict):\n raise QueryParseError(\n \"Query should be a YAML object describing the URL to query.\"\n )",
" if \"url\" not in query:\n raise QueryParseError(\"Query must include 'url' option.\")\n",
"",
"\n method = query.get(\"method\", \"get\")\n request_options = project(query, (\"params\", \"headers\", \"data\", \"auth\", \"json\"))",
" fields = query.get(\"fields\")\n path = query.get(\"path\")",
" if isinstance(request_options.get(\"auth\", None), list):\n request_options[\"auth\"] = tuple(request_options[\"auth\"])\n elif self.configuration.get(\"username\") or self.configuration.get(\"password\"):\n request_options[\"auth\"] = (\n self.configuration.get(\"username\"),\n self.configuration.get(\"password\"),\n )",
" if method not in (\"get\", \"post\"):\n raise QueryParseError(\"Only GET or POST methods are allowed.\")",
" if fields and not isinstance(fields, list):\n raise QueryParseError(\"'fields' needs to be a list.\")",
" response, error = self.get_response(\n query[\"url\"], http_method=method, **request_options\n )",
" if error is not None:\n return None, error",
" data = json_dumps(parse_json(response.json(), path, fields))",
" if data:\n return data, None\n else:\n return None, \"Got empty response from '{}'.\".format(query[\"url\"])",
"\nregister(JSON)"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import requests",
"from redash import settings\n",
"",
"",
"class ConfiguredSession(requests.Session):",
" def request(self, *args, **kwargs):\n if not settings.REQUESTS_ALLOW_REDIRECTS:\n kwargs.update({\"allow_redirects\": False})\n return super().request(*args, **kwargs)",
"\nrequests_session = ConfiguredSession()"
] |
[
0,
1,
0,
1,
0,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"",
"from redash import settings\n",
"from advocate.exceptions import UnacceptableAddressException\nif settings.ENFORCE_PRIVATE_ADDRESS_BLOCK:\n import advocate as requests_or_advocate\nelse:\n import requests as requests_or_advocate",
"",
"",
"class ConfiguredSession(requests_or_advocate.Session):",
" def request(self, *args, **kwargs):\n if not settings.REQUESTS_ALLOW_REDIRECTS:\n kwargs.update({\"allow_redirects\": False})\n return super().request(*args, **kwargs)",
"\nrequests_session = ConfiguredSession()"
] |
[
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"google-api-python-client==1.7.11\nprotobuf==3.17.3\ngspread==3.1.0\nimpyla==0.16.0\ninfluxdb==5.2.3\nmysqlclient==1.3.14\noauth2client==4.1.3\npyhive==0.6.1\npymongo[tls,srv]==3.9.0\nvertica-python==0.9.5\ntd-client==1.0.0\npymssql==2.1.4\ndql==0.5.26\ndynamo3==0.4.10\nboto3>=1.10.0,<1.11.0\nbotocore>=1.13,<1.14.0\nsasl>=0.1.3\nthrift>=0.8.0\nthrift_sasl>=0.1.0\ncassandra-driver==3.21.0\nmemsql==3.0.0\natsd_client==3.0.5\nsimple_salesforce==0.74.3\nPyAthena>=1.5.0\npymapd==0.19.0\nqds-sdk>=1.9.6\nibm-db>=2.0.9\npydruid==0.5.7\nrequests_aws_sign==0.1.5\nsnowflake-connector-python==2.1.3\nphoenixdb==0.7\n# certifi is needed to support MongoDB and SSL:\ncertifi>=2019.9.11\npydgraph==2.0.2\nazure-kusto-data==0.0.35\npyexasol==0.12.0\npython-rapidjson==0.8.0\npyodbc==4.0.28\ntrino~=0.305\ncmem-cmempy==21.2.3\nxlrd==2.0.1\nopenpyxl==3.0.7\nfirebolt-sqlalchemy",
""
] |
[
1,
0
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"google-api-python-client==1.7.11\nprotobuf==3.17.3\ngspread==3.1.0\nimpyla==0.16.0\ninfluxdb==5.2.3\nmysqlclient==1.3.14\noauth2client==4.1.3\npyhive==0.6.1\npymongo[tls,srv]==3.9.0\nvertica-python==0.9.5\ntd-client==1.0.0\npymssql==2.1.4\ndql==0.5.26\ndynamo3==0.4.10\nboto3>=1.10.0,<1.11.0\nbotocore>=1.13,<1.14.0\nsasl>=0.1.3\nthrift>=0.8.0\nthrift_sasl>=0.1.0\ncassandra-driver==3.21.0\nmemsql==3.0.0\natsd_client==3.0.5\nsimple_salesforce==0.74.3\nPyAthena>=1.5.0\npymapd==0.19.0\nqds-sdk>=1.9.6\nibm-db>=2.0.9\npydruid==0.5.7\nrequests_aws_sign==0.1.5\nsnowflake-connector-python==2.1.3\nphoenixdb==0.7\n# certifi is needed to support MongoDB and SSL:\ncertifi>=2019.9.11\npydgraph==2.0.2\nazure-kusto-data==0.0.35\npyexasol==0.12.0\npython-rapidjson==0.8.0\npyodbc==4.0.28\ntrino~=0.305\ncmem-cmempy==21.2.3\nxlrd==2.0.1\nopenpyxl==3.0.7\nfirebolt-sqlalchemy",
"advocate==1.0.0"
] |
[
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import mock\nfrom unittest import TestCase\n",
"from redash.utils.requests_session import requests, ConfiguredSession",
"from redash.query_runner import BaseHTTPQueryRunner",
"\nclass RequiresAuthQueryRunner(BaseHTTPQueryRunner):\n requires_authentication = True",
"\nclass TestBaseHTTPQueryRunner(TestCase):\n def test_requires_authentication_default(self):\n self.assertFalse(BaseHTTPQueryRunner.requires_authentication)\n schema = BaseHTTPQueryRunner.configuration_schema()\n self.assertNotIn(\"username\", schema[\"required\"])\n self.assertNotIn(\"password\", schema[\"required\"])",
" def test_requires_authentication_true(self):\n schema = RequiresAuthQueryRunner.configuration_schema()\n self.assertIn(\"username\", schema[\"required\"])\n self.assertIn(\"password\", schema[\"required\"])",
" def test_get_auth_with_values(self):\n query_runner = BaseHTTPQueryRunner(\n {\"username\": \"username\", \"password\": \"password\"}\n )\n self.assertEqual(query_runner.get_auth(), (\"username\", \"password\"))",
" def test_get_auth_empty(self):\n query_runner = BaseHTTPQueryRunner({})\n self.assertIsNone(query_runner.get_auth())",
" def test_get_auth_empty_requires_authentication(self):\n query_runner = RequiresAuthQueryRunner({})\n self.assertRaisesRegex(\n ValueError, \"Username and Password required\", query_runner.get_auth\n )",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_success(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 200\n mock_response.text = \"Success\"\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertEqual(response.status_code, 200)\n self.assertIsNone(error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_success_custom_auth(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 200\n mock_response.text = \"Success\"\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n auth = (\"username\", \"password\")\n response, error = query_runner.get_response(url, auth=auth)\n mock_get.assert_called_once_with(\"get\", url, auth=auth)\n self.assertEqual(response.status_code, 200)\n self.assertIsNone(error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_failure(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 301\n mock_response.text = \"Redirect\"\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIn(query_runner.response_error, error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_httperror_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"",
" http_error = requests.HTTPError()",
" mock_response.raise_for_status.side_effect = http_error\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIsNotNone(error)\n self.assertIn(\"Failed to execute query\", error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_requests_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"\n exception_message = \"Some requests exception\"",
" requests_exception = requests.RequestException(exception_message)",
" mock_response.raise_for_status.side_effect = requests_exception\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIsNotNone(error)\n self.assertEqual(exception_message, error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_generic_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"\n exception_message = \"Some generic exception\"\n exception = ValueError(exception_message)\n mock_response.raise_for_status.side_effect = exception\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n self.assertRaisesRegex(\n ValueError, exception_message, query_runner.get_response, url\n )"
] |
[
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import mock\nfrom unittest import TestCase\n",
"from redash.utils.requests_session import requests_or_advocate, ConfiguredSession",
"from redash.query_runner import BaseHTTPQueryRunner",
"\nclass RequiresAuthQueryRunner(BaseHTTPQueryRunner):\n requires_authentication = True",
"\nclass TestBaseHTTPQueryRunner(TestCase):\n def test_requires_authentication_default(self):\n self.assertFalse(BaseHTTPQueryRunner.requires_authentication)\n schema = BaseHTTPQueryRunner.configuration_schema()\n self.assertNotIn(\"username\", schema[\"required\"])\n self.assertNotIn(\"password\", schema[\"required\"])",
" def test_requires_authentication_true(self):\n schema = RequiresAuthQueryRunner.configuration_schema()\n self.assertIn(\"username\", schema[\"required\"])\n self.assertIn(\"password\", schema[\"required\"])",
" def test_get_auth_with_values(self):\n query_runner = BaseHTTPQueryRunner(\n {\"username\": \"username\", \"password\": \"password\"}\n )\n self.assertEqual(query_runner.get_auth(), (\"username\", \"password\"))",
" def test_get_auth_empty(self):\n query_runner = BaseHTTPQueryRunner({})\n self.assertIsNone(query_runner.get_auth())",
" def test_get_auth_empty_requires_authentication(self):\n query_runner = RequiresAuthQueryRunner({})\n self.assertRaisesRegex(\n ValueError, \"Username and Password required\", query_runner.get_auth\n )",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_success(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 200\n mock_response.text = \"Success\"\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertEqual(response.status_code, 200)\n self.assertIsNone(error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_success_custom_auth(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 200\n mock_response.text = \"Success\"\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n auth = (\"username\", \"password\")\n response, error = query_runner.get_response(url, auth=auth)\n mock_get.assert_called_once_with(\"get\", url, auth=auth)\n self.assertEqual(response.status_code, 200)\n self.assertIsNone(error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_failure(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 301\n mock_response.text = \"Redirect\"\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIn(query_runner.response_error, error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_httperror_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"",
" http_error = requests_or_advocate.HTTPError()",
" mock_response.raise_for_status.side_effect = http_error\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIsNotNone(error)\n self.assertIn(\"Failed to execute query\", error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_requests_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"\n exception_message = \"Some requests exception\"",
" requests_exception = requests_or_advocate.RequestException(exception_message)",
" mock_response.raise_for_status.side_effect = requests_exception\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIsNotNone(error)\n self.assertEqual(exception_message, error)",
" @mock.patch.object(ConfiguredSession, \"request\")\n def test_get_response_generic_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"\n exception_message = \"Some generic exception\"\n exception = ValueError(exception_message)\n mock_response.raise_for_status.side_effect = exception\n mock_get.return_value = mock_response",
" url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n self.assertRaisesRegex(\n ValueError, exception_message, query_runner.get_response, url\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [316, 90, 86, 168, 6, 43, 105], "buggy_code_start_loc": [16, 3, 3, 5, 1, 43, 4], "filenames": ["redash/query_runner/__init__.py", "redash/query_runner/csv.py", "redash/query_runner/excel.py", "redash/query_runner/json_ds.py", "redash/utils/requests_session.py", "requirements_all_ds.txt", "tests/query_runner/test_http.py"], "fixing_code_end_loc": [312, 91, 88, 166, 12, 45, 105], "fixing_code_start_loc": [16, 2, 2, 5, 0, 44, 4], "message": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redash:redash:*:*:*:*:*:*:*:*", "matchCriteriaId": "AF2C7DBC-5166-4A5C-8691-ED5E0EE3B027", "versionEndExcluding": "10.0.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redash is a package for data visualization and sharing. In versions 10.0 and priorm the implementation of URL-loading data sources like JSON, CSV, or Excel is vulnerable to advanced methods of Server Side Request Forgery (SSRF). These vulnerabilities are only exploitable on installations where a URL-loading data source is enabled. As of time of publication, the `master` and `release/10.x.x` branches address this by applying the Advocate library for making http requests instead of the requests library directly. Users should upgrade to version 10.0.1 to receive this patch. There are a few workarounds for mitigating the vulnerability without upgrading. One can disable the vulnerable data sources entirely, by adding the following env variable to one's configuration, making them unavailable inside the webapp. One can switch any data source of certain types (viewable in the GitHub Security Advisory) to be `View Only` for all groups on the Settings > Groups > Data Sources screen. For users unable to update an admin may modify Redash's configuration through environment variables to mitigate this issue. Depending on the version of Redash, an admin may also need to run a CLI command to re-encrypt some fields in the database. The `master` and `release/10.x.x` branches as of time of publication have removed the default value for `REDASH_COOKIE_SECRET`. All future releases will also require this to be set explicitly. For existing installations, one will need to ensure that explicit values are set for the `REDASH_COOKIE_SECRET` and `REDASH_SECRET_KEY `variables."}, {"lang": "es", "value": "Redash es un paquete para visualizar y compartir datos. En las versiones 10.0 y anteriores, la implementaci\u00f3n de fuentes de datos de carga de URL como JSON, CSV o Excel es vulnerable a m\u00e9todos avanzados de falsificaci\u00f3n de peticiones del lado del servidor (SSRF). Estas vulnerabilidades s\u00f3lo pueden ser explotadas en instalaciones en las que est\u00e9 habilitada una fuente de datos de carga por URL. En el momento de la publicaci\u00f3n, las ramas \"master\" y \"release/10.x.x\" abordan esto aplicando la biblioteca Advocate para realizar peticiones http en lugar de la biblioteca requests directamente. Los usuarios deben actualizar a la versi\u00f3n 10.0.1 para recibir este parche. Se presentan algunas soluciones para mitigar la vulnerabilidad sin actualizar. Uno puede deshabilitar las fuentes de datos vulnerables por completo, a\u00f1adiendo la siguiente variable env a la configuraci\u00f3n, haciendo que no est\u00e9n disponibles dentro de la aplicaci\u00f3n web. Puede cambiarse cualquier fuente de datos de determinados tipos (visibles en el Aviso de Seguridad de GitHub) para que sea \"View Only\" para todos los grupos en la pantalla de Settings ) Groups ) Data Sources. Para usuarios que no pueden actualizar un administrador puede modificar la configuraci\u00f3n de Redash mediante variables de entorno para mitigar este problema. Dependiendo de la versi\u00f3n de Redash, un administrador tambi\u00e9n puede necesitar ejecutar un comando CLI para volver a cifrar algunos campos en la base de datos. Las ramas \"master\" y \"release/10.x.x\" en el momento de la publicaci\u00f3n han eliminado el valor por defecto de \"REDASH_COOKIE_SECRET\". Todas las versiones futuras tambi\u00e9n requerir\u00e1n que sea establecida expl\u00edcitamente. Para las instalaciones existentes, habr\u00e1 que asegurarse de que sean establecidos valores expl\u00edcitos para las variables \"REDASH_COOKIE_SECRET\" y \"REDASH_SECRET_KEY\""}], "evaluatorComment": null, "id": "CVE-2021-43780", "lastModified": "2021-11-30T15:07:27.213", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "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": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 1.6, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-11-24T16:15:14.337", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/getredash/redash/security/advisories/GHSA-fcpv-hgq6-87h7"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/getredash/redash/commit/61bbb5aa7a23a93f2f93710005f71bc972826099"}, "type": "CWE-918"}
| 311
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"// Pitchfork ctx defines the context that is passed through Pitchfork pertaining primarily to the logged in, selected user/group\npackage pitchfork",
"import (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"",
"\tuseragent \"github.com/mssola/user_agent\"\n\ti18n \"github.com/nicksnyder/go-i18n/i18n\"\n)",
"// ErrLoginIncorrect is used when a login is incorrect, this to hide more specific reasons\nvar ErrLoginIncorrect = errors.New(\"Login incorrect\")",
"// PfNewUserI, NewGroupI, PfMenuI, PfAppPermsI, PfPostBecomeI are function definitions to allow overriding of these functions by application code\ntype PfNewUserI func() (user PfUser)\ntype PfNewGroupI func() (user PfGroup)\ntype PfMenuI func(ctx PfCtx, menu *PfMenu)\ntype PfAppPermsI func(ctx PfCtx, what string, perms Perm) (final bool, ok bool, err error)\ntype PfPostBecomeI func(ctx PfCtx)",
"// PfModOptsI is the interface that is implemented by PfModOptsS allowing the latter to be extended with more details\ntype PfModOptsI interface {\n\tIsModOpts() bool\n}",
"// PfModOptsS is the base structure used to impleent PfModOptsI\ntype PfModOptsS struct {\n\t// CLI command prefix, eg 'group wiki'\n\tCmdpfx string",
"\t// URL prefix, typically System_Get().PublicURL()\n\tURLpfx string",
"\t// Path Root\n\tPathroot string",
"\t// URL root, inside the hostname, eg '/group/name/wiki/'\n\tURLroot string\n}",
"// IsModOpts is a simple fakeish function to cause PfModOptsS to be of type PfModOptsI\n// as it requires this function to be present, which other structures will not satisfy.\nfunc (m PfModOptsS) IsModOpts() bool {\n\treturn true\n}",
"// PfModOpts can be used to easily initialize a PfModOptsS.\n//\n// The arguments match the variables in the PfModOpts structure.\n//\n// The function ensures that the web_root ends in a slash ('/').\nfunc PfModOpts(ctx PfCtx, cmdpfx string, path_root string, web_root string) PfModOptsS {\n\turlpfx := System_Get().PublicURL",
"\tweb_root = URL_EnsureSlash(web_root)",
"\treturn PfModOptsS{cmdpfx, urlpfx, path_root, web_root}\n}",
"// PfCtx is the Context Interface.\n//\n// PfCtxS is the default implementation.\n//\n// This interface is primarily intended to allow extension by an application.",
"// See the individual functions in PfCtxS for per function details.\ntype PfCtx interface {\n\tGetAbort() <-chan bool\n\tSetAbort(abort <-chan bool)\n\tSetTx(tx *Tx)\n\tGetTx() (tx *Tx)\n\tErr(message string)\n\tErrf(format string, a ...interface{})\n\tLog(message string)\n\tLogf(format string, a ...interface{})\n\tDbg(message string)\n\tDbgf(format string, a ...interface{})\n\tInit() (err error)\n\tSetStatus(code int)\n\tGetStatus() (code int)\n\tSetReturnCode(rc int)\n\tGetReturnCode() (rc int)\n\tGetLoc() string\n\tGetLastPart() string\n\tBecome(user PfUser)\n\tGetToken() (tok string)\n\tNewToken() (err error)\n\tLoginToken(tok string) (expsoon bool, err error)\n\tLogin(username string, password string, twofactor string) (err error)\n\tLogout()\n\tIsLoggedIn() bool\n\tIsGroupMember() bool\n\tIAmGroupAdmin() bool\n\tIAmGroupMember() bool\n\tGroupHasWiki() bool\n\tGroupHasFile() bool\n\tGroupHasCalendar() bool\n\tSwapSysAdmin() bool\n\tIsSysAdmin() bool\n\tCheckPerms(what string, perms Perm) (ok bool, err error)\n\tCheckPermsT(what string, permstr string) (ok bool, err error)\n\tTheUser() (user PfUser)\n\tSelectedSelf() bool\n\tSelectedUser() (user PfUser)\n\tSelectedGroup() (grp PfGroup)\n\tSelectedML() (ml PfML)\n\tSelectedEmail() (email PfUserEmail)\n\tHasSelectedUser() bool\n\tHasSelectedGroup() bool\n\tHasSelectedML() bool\n\tSelectMe()\n\tSelectUser(username string, perms Perm) (err error)\n\tSelectGroup(gr_name string, perms Perm) (err error)\n\tSelectML(ml_name string, perms Perm) (err error)\n\tSelectEmail(email string) (err error)\n\tSetModOpts(opts PfModOptsI)\n\tGetModOpts() (opts interface{})\n\tPDbgf(what string, perm Perm, format string, a ...interface{})\n\tOut(txt string)\n\tOutf(format string, a ...interface{})\n\tOutLn(format string, a ...interface{})\n\tSetOutUnbuffered(obj interface{}, fun string)\n\tOutBuffered(on bool)\n\tIsBuffered() bool\n\tBuffered() (o string)\n\tGetRemote() (remote string)\n\tSetClient(clientip net.IP, remote string, ua string)\n\tGetClientIP() net.IP\n\tGetUserAgent() (string, string, string)\n\tSelectObject(obj *interface{})\n\tSelectedObject() (obj *interface{})\n\tGetLanguage() string\n\tSetLanguage(name string)\n\tGetTfunc() i18n.TranslateFunc",
"\t// User and Group creation overrides\n\tNewUser() (user PfUser)\n\tNewUserI() (i interface{})\n\tNewGroup() (user PfGroup)\n\tNewGroupI() (i interface{})",
"\t// Menu Overrides\n\tMenuOverride(menu *PfMenu)",
"\t// Menu Related (menu.go)\n\tMenu(args []string, menu PfMenu) (err error)\n\tWalkMenu(args []string) (menu *PfMEntry, err error)\n\tCmd(args []string) (err error)\n\tCmdOut(cmd string, args []string) (msg string, err error)\n\tBatch(filename string) (err error)",
"\t// Application Data\n\tSetAppData(data interface{})\n\tGetAppData() interface{}\n}",
"// SessionClaims describe claims for a session\ntype SessionClaims struct {\n\tJWTClaims\n\tUserDesc string `json:\"userdesc\"`\n\tIsSysAdmin bool `json:\"issysadmin\"`\n}",
"// PfCtxS is the default implementation of PfCtx\ntype PfCtxS struct {\n\tabort <-chan bool /* Abort the request */\n\tstatus int /* HTTP Status code */\n\treturncode int /* Command Line return code */\n\tloc string /* Command tree location */\n\toutput string /* Output buffer */\n\tmode_buffered bool /* Buffering of output in effect */\n\tuser PfUser /* Authenticated User */\n\tis_sysadmin bool /* Whether the user's sysadmin priveleges are enabled */\n\ttoken string /* The authentication token */\n\ttoken_claims SessionClaims /* Parsed Token Claims */\n\tremote string /* The address of the client, including X-Forwarded-For */\n\tclient_ip net.IP /* Client's IP addresses */\n\tua_full string /* The HTTP User Agent */\n\tua_browser string /* HTTP User Agent: Browser */\n\tua_os string /* HTTP User Agent: Operating System */\n\tlanguage string /* User's chosen language (TODO: Allow user to select it) */\n\ttfunc i18n.TranslateFunc /* Translation function populated with current language */\n\tsel_user PfUser /* Selected User */\n\tsel_group PfGroup /* Selected Group */\n\tsel_ml *PfML /* Selected Mailing List */\n\tsel_email *PfUserEmail /* Selected User email address */\n\tsel_obj *interface{} /* Selected Object (ctx + struct only) */\n\tmod_opts interface{} /* Module Options for Messages/Wiki/Files etc */\n\tf_newuser PfNewUserI /* Create a new User */\n\tf_newgroup PfNewGroupI /* Create a new Group */\n\tf_menuoverride PfMenuI /* Override a menu */\n\tf_appperms PfAppPermsI /* Application Permission Check */\n\tf_postbecome PfPostBecomeI /* Post Become() */",
"\t// Unbuffered Output */\n\toutunbuf_fun string // Function name that handles unbuffered output */\n\toutunbuf_obj ObjFuncI // Object where the function lives */",
"\t// Database internal\n\tdb_Tx *Tx // Used for database transactions",
"\t// Menu internal values (menu.go)\n\tmenu_walkonly bool // Set to 'true' to indicate that only walk, do not execute; used for figuring out what arguments are needed\n\tmenu_args []string // Which arguments are currently requested\n\tmenu_menu *PfMEntry // Current menu entry being attempted",
"\t/* Application Data */\n\tappdata interface{} // Application specific data\n}",
"// PfNewCtx allows overriding the NewCtx function, thus allowing extending PfCtx\ntype PfNewCtx func() PfCtx",
"// NewPfCtx is used to initialize a new Pitchfork Context.\n//\n// The various arguments are all to provide the ability to replace\n// standard Pitchfork functions with application specific ones that\n// likely extends the Pitchfork functionality or that carry extra details.\n//\n// newuser is used as a function for creating new users.\n//\n// newgroup is used as a function for creating new groups.\n//\n// menuoverride is used as a function to override menu entries.\n//\n// appperms is used as a function to verify application specific permissions.\n//\n// postbecome is used as a callback after a user has changed (eg when logging in).\n//\n// All overrides are optional, and will be defaulted to the Pitchfork versions\n// when they are provided as 'nil'.\n//\n// NewPfCtx is called from the constructors of PfUI and, except for testing\n// should rarely be called directly as the context is already handed to a function.\nfunc NewPfCtx(newuser PfNewUserI, newgroup PfNewGroupI, menuoverride PfMenuI, appperms PfAppPermsI, postbecome PfPostBecomeI) PfCtx {\n\tif newuser == nil {\n\t\tnewuser = NewPfUserA\n\t}",
"\tif newgroup == nil {\n\t\tnewgroup = NewPfGroup\n\t}",
"\ttfunc, err := i18n.Tfunc(Config.TransDefault)\n\tif err != nil {\n\t\ttfunc = nil\n\t}",
"\treturn &PfCtxS{f_newuser: newuser,\n\t\tf_newgroup: newgroup, f_menuoverride: menuoverride, f_appperms: appperms,\n\t\tf_postbecome: postbecome,\n\t\tlanguage: Config.TransDefault, mode_buffered: true, tfunc: tfunc}\n}",
"// GetAbort is used to retrieve the abort channel (as used/passed-down from the HTTP handler)\n//\n// This channel is used to indicate, by the HTTP library, that the HTTP client has\n// disconnected and that the request can be aborted as the client will never receive\n// the answer of the query.\n//\n// Used amongst others by the search infrastructure.\nfunc (ctx *PfCtxS) GetAbort() <-chan bool {\n\treturn ctx.abort\n}",
"// SetAbort is used to set the abort channel (as used/passed-down from the HTTP handler).\n//\n// SetAbort is called from H_root() to configure the abort channel as passed down\n// from the Golang HTTP package.\nfunc (ctx *PfCtxS) SetAbort(abort <-chan bool) {\n\tctx.abort = abort\n}",
"// GetLanguage is used to retrieve the user-selected language setting\n//\n// The returned string is in the form of a RFC2616 Accept-Language header.\n// Typically it will be 'en-us', or sometimes 'de', 'de-DE', 'de-CH' or 'es'.\nfunc (ctx *PfCtxS) GetLanguage() string {\n\treturn ctx.language\n}",
"// SetLanguage accepts a RFC2616 style Accept-Language string\n// it then uses that information to determine the best language\n// to return.\nfunc (ctx *PfCtxS) SetLanguage(name string) {\n\tctx.language = name\n\ttfunc, err := i18n.Tfunc(name, Config.TransDefault)\n\tif err != nil {\n\t\t// XXX: Handle properly, this crashes the goproc based on invalid Accept-Language header\n\t\t// The panic might expose information to the enduser\n\t\tpanic(err.Error())\n\t}\n\tctx.tfunc = tfunc\n}",
"// GetTfunc returns the translation function\nfunc (ctx *PfCtxS) GetTfunc() i18n.TranslateFunc {\n\treturn ctx.tfunc\n}",
"// SetAppData can be used to set the appdata of a context.\n//\n// Typically this is used by an application's edition of a context to store\n// itself in the pitchfork context. This given that Golang does not support\n// polymorphism and thus needs a place to hide the full version of itself.\nfunc (ctx *PfCtxS) SetAppData(appdata interface{}) {\n\tctx.appdata = appdata\n}",
"// GetAppData is used for getting application specific data inside the context.\n//\n// Typically this is used by an application's edition of a context to retrieve\n// itself from the pitchfork context. This given that Golang does not support\n// polymorphism and it needs to retrieve itself from the embedded edition of itself.\nfunc (ctx *PfCtxS) GetAppData() interface{} {\n\treturn ctx.appdata\n}",
"// NewUser causes a new PfUser (or extended edition) to be created.\n//\n// The override for NewUser, as configured at Ctx creation time is used\n// thus allowing the application specific Ctx to be returned.\nfunc (ctx *PfCtxS) NewUser() PfUser {\n\treturn ctx.f_newuser()\n}",
"// NewUserI is like NewUser() but returns a generic interface */\nfunc (ctx *PfCtxS) NewUserI() interface{} {\n\treturn ctx.f_newuser()\n}",
"// NewGroup causes a new PfGroup to be created by calling the\n// application defined edition of a NewGroup function.\nfunc (ctx *PfCtxS) NewGroup() PfGroup {\n\treturn ctx.f_newgroup()\n}",
"// NewGroupI is like NewGroup() but returns a generic interface\nfunc (ctx *PfCtxS) NewGroupI() interface{} {\n\treturn ctx.f_newgroup()\n}",
"// MenuOverride is called before a menu is further processed,\n// allowing entries to be modified by calling the callback.\n//\n// As noted, it is an optional override.\nfunc (ctx *PfCtxS) MenuOverride(menu *PfMenu) {\n\tif ctx.f_menuoverride != nil {\n\t\tctx.f_menuoverride(ctx, menu)\n\t}\n}",
"// SetTx is used by the database code to select the current transaction\nfunc (ctx *PfCtxS) SetTx(tx *Tx) {\n\tctx.db_Tx = tx\n}",
"// GetTx is used by the database code to get the current transaction\nfunc (ctx *PfCtxS) GetTx() (tx *Tx) {\n\treturn ctx.db_Tx\n}",
"// GetRemote retrieves the remote address of the user/connection.\n//\n// The address is a IPv4 or IPv6 textual representation.\nfunc (ctx *PfCtxS) GetRemote() (remote string) {\n\treturn ctx.remote\n}",
"// SetClient is used for configuring the client IP, remote address and Full User Agent strings.\n//\n// Typically not called from an application, but from cui's SetClientIP()\n// which in turn gets called from the H_root.\n//\n// The clientip is a pre-parsed IP address and XFF-filtered hops.\n//\n// Remote contains the full IP address string (including X-Forwarded-For hops).\n//\n// Fullua contains the HTTP User-Agent header.\n//\n// This function sets the variables of the Ctx (client_ip, remote) and parses\n// the Fullua (Full User-Agent) variable, storing the details in Ctx.\nfunc (ctx *PfCtxS) SetClient(clientip net.IP, remote string, fullua string) {\n\tctx.client_ip = clientip\n\tctx.remote = remote",
"\t/* Split the UA in several parts */\n\tua := useragent.New(fullua)\n\tctx.ua_full = fullua\n\tif ua != nil {\n\t\tctx.ua_browser, _ = ua.Browser()\n\t\tctx.ua_os = ua.OS()\n\t} else {\n\t\t/* Did not parse as it is the CLI */\n\t\tif clientip.IsLoopback() {\n\t\t\tctx.ua_browser = \"Tickly\"\n\t\t\tctx.ua_os = \"Trident\"\n\t\t} else {\n\t\t\tctx.ua_browser = \"unknown\"\n\t\t\tctx.ua_os = \"unknown\"\n\t\t}\n\t}\n}",
"// GetClientIP is used to get the client's IP address\nfunc (ctx *PfCtxS) GetClientIP() net.IP {\n\treturn ctx.client_ip\n}",
"// GetUserAgent is used for retrieving the parsed User Agent; see also SetClient()\nfunc (ctx *PfCtxS) GetUserAgent() (string, string, string) {\n\treturn ctx.ua_full, ctx.ua_browser, ctx.ua_os\n}",
"// SelectObject is used by the struct code (lib/struct.go) to set the\n// object that it wants to keep track of during parsing.\nfunc (ctx *PfCtxS) SelectObject(obj *interface{}) {\n\tctx.sel_obj = obj\n}",
"// SelectedObject is used by the struct code to retrieve\n// the object it is currently parsing.\nfunc (ctx *PfCtxS) SelectedObject() (obj *interface{}) {\n\treturn ctx.sel_obj\n}",
"// SetModOpts allows setting the options for the wiki and file modules\nfunc (ctx *PfCtxS) SetModOpts(opts PfModOptsI) {\n\tctx.mod_opts = opts\n}",
"// GetModOpts allows getting the options for the wiki and file modules\nfunc (ctx *PfCtxS) GetModOpts() (opts interface{}) {\n\treturn ctx.mod_opts\n}",
"// Perm is used for storing the OR value of permissions\n//\n// Note: Keep in sync with permnames && ui/ui (convenience for all the menus there).\n//\n// It is used as a bitfield, hence multiple perms are possible by ORing them together.\n// Check access using the CheckPerms() function.\n//\n// The perms use the context's sel_{user|group|ml|*} variables to check if those permissions match.\n//\n// Being a SysAdmin overrides almost all permissions!\n//\n// Change the 'false' in PDbg to 'true' to see what permission decisions are being made.\n//\n// Application permissions are fully handled by the application.\n// See the CheckPerms function for more details.\ntype Perm uint64",
"// PERM_* define the permissions in the system.\n//\n// Each permission tests as true when the given condition is met.\n// See the per permission desciption for what condition they test for.\n//\n// The permissions are listed from weak (NONE) to strong (NOBODY).\n//\n// Permissions can be ORed together, the strongest are tested first.\n//\n// Not all combinations will make sense. eg combining PERM_GUEST|PERM_USER\n// means that both not-loggedin and loggedin users have access, at which\n// point the check can just be replaced with PERM_NONE.\n//\n// Application permissions our application specific.\n//\n// The PERM_'s marked 'Flag' are not used for checking permissions\n// but used for modifying the behavior of a menu entry.",
"const (\n\tPERM_NOTHING Perm = 0 // Nothing / empty permissions, primarily used for initialization, should not be found in code as it indicates that the Permission was not configured and thus should normally not be used\n\tPERM_NONE Perm = 1 << iota // No permissions needed (authenticated or unauthenticated is okay), typically combined with the a Flag like PERM_HIDDEN or PERM_NOSUBS\n\tPERM_GUEST // Tests that the user is not authenticated: The user is a Guest of the system; does not accept authenticated sessions\n\tPERM_USER // Tests that the user is logged in: the user has authenticated\n\tPERM_USER_SELF // Tests that the selected user matches the logged in user\n\tPERM_USER_NOMINATE // Tests that the user can nominate the selected user\n\tPERM_USER_VIEW // Tests that the user can view the selected user\n\tPERM_GROUP_MEMBER // Tests that the selected user is an active member of the selected group that can see the group\n\tPERM_GROUP_ADMIN // Tests that the selected user is an Admin of the selected group\n\tPERM_GROUP_WIKI // Tests that the selected Group has the Wiki section enabled\n\tPERM_GROUP_FILE // Tests that the selected Group has the File section enabled\n\tPERM_GROUP_CALENDAR // Tests that the selected Group has the Calendar section enabled\n\tPERM_SYS_ADMIN // Tests that the user is a System Administrator\n\tPERM_SYS_ADMIN_CAN // Can be a System Administrator\n\tPERM_CLI // Tests when the CLI option is enabled in system settings\n\tPERM_API // Tests when the API option is enabled in system settings\n\tPERM_OAUTH // Tests when the OAUTH option is enabled in system settings\n\tPERM_LOOPBACK // Tests that the connection comes from loopback (127.0.0.1 / ::1 as the Client/Remote IP address)\n\tPERM_HIDDEN // Flag: The menu option is hidden\n\tPERM_NOCRUMB // Flag: Don't add a crumb for this menu\n\tPERM_NOSUBS // Flag: No sub menus for this menu entry. See the NoSubs function for more details.\n\tPERM_NOBODY // Absolutely nobody has access (highest priority, first checked)",
"\t// Application permissions - defined by the application\n\tPERM_APP_0\n\tPERM_APP_1\n\tPERM_APP_2\n\tPERM_APP_3\n\tPERM_APP_4\n\tPERM_APP_5\n\tPERM_APP_6\n\tPERM_APP_7\n\tPERM_APP_8\n\tPERM_APP_9\n)",
"// permnames contains the human readable names matching the permissions\nvar permnames []string",
"// init is used to initialize permnames and verify that they are correct, at least in count\nfunc init() {\n\tpermnames = []string{\n\t\t\"nothing\",\n\t\t\"none\",\n\t\t\"guest\",\n\t\t\"user\",\n\t\t\"self\",\n\t\t\"user_nominate\",\n\t\t\"user_view\",\n\t\t\"group_member\",\n\t\t\"group_admin\",\n\t\t\"group_wiki\",\n\t\t\"group_file\",\n\t\t\"group_calendar\",\n\t\t\"sysadmin\",\n\t\t\"sysadmin_can\",\n\t\t\"cli\",\n\t\t\"api\",\n\t\t\"oauth\",\n\t\t\"loopback\",\n\t\t\"hidden\",\n\t\t\"nocrumb\",\n\t\t\"nosubs\",\n\t\t\"nobody\",\n\t\t\"app_0\",\n\t\t\"app_1\",\n\t\t\"app_2\",\n\t\t\"app_3\",\n\t\t\"app_4\",\n\t\t\"app_5\",\n\t\t\"app_6\",\n\t\t\"app_7\",\n\t\t\"app_9\",\n\t}",
"\t// Verify that the correct amount of permissions is present\n\tmax := uint64(1 << uint64(len(permnames)))\n\tif max != uint64(PERM_APP_9) {\n\t\tfmt.Printf(\"Expected %d got %d\\n\", max, PERM_APP_9)\n\t\tpanic(\"Invalid permnames\")\n\t}\n}",
"// Shortcutted commonly used HTTP error codes\nconst (\n\tStatusOK = 200\n\tStatusUnauthorized = 401\n)",
"// Debug is a Global Debug flag, used primarily for determining if debug messages should be output. Typically toggled by flags\nvar Debug = false",
"// Init is the \"constructor\" for Pitchfork Contexts\nfunc (ctx *PfCtxS) Init() (err error) {\n\t// Default HTTP status\n\tctx.status = StatusOK",
"\t// Default Shell Return Code to 0\n\tctx.returncode = 0",
"\treturn err\n}",
"// SetStatus can be used by a h_* function to set the status of the context.\n//\n// The status typically matches a HTTP error (eg StatusNotFound from golang HTTP library).\n//\n// The final status is flushed out during UI's Flush() time.\n//\n// The status code is tracked in lib instead of the UI layer to allow a generic\n// status code system inside Pitchfork.\nfunc (ctx *PfCtxS) SetStatus(code int) {\n\tctx.status = code\n}",
"// GetStatus can be used to get the status of the context.\n//\n// Typically only called by UI Flush(), but in theory could be used\n// by an application/function to check the current error code too.\nfunc (ctx *PfCtxS) GetStatus() (code int) {\n\treturn ctx.status\n}",
"// SetReturnCode is used by the CLI edition of tools to return a Shell Return Code.\nfunc (ctx *PfCtxS) SetReturnCode(rc int) {\n\tctx.returncode = rc\n}",
"// GetReturnCode is used by the CLI edition of tools to fetch the set Shell Return Code.\n//\n// During UI Flush() this error code is fetched and when not-0 reported as X-ReturnCode.\nfunc (ctx *PfCtxS) GetReturnCode() (rc int) {\n\treturn ctx.returncode\n}",
"// GetLoc returns where in the CLI menu system our code is located (XXX: Improve naming).\n//\n// This function is typically called by MenuOverrides so that they can determine\n// where they are and thus what they might want to change.\nfunc (ctx *PfCtxS) GetLoc() string {\n\treturn ctx.loc\n}",
"// GetLastPart is used to get the last portion of the location (XXX: Improve naming).\nfunc (ctx *PfCtxS) GetLastPart() string {\n\tfa := strings.Split(ctx.loc, \" \")\n\treturn fa[len(fa)-1]\n}",
"// Become can be used to become the given user.\n//\n// The context code that logs in a user uses this.\n// This can be used for a 'sudo' type mechanism as is cmd/setup/sudo.go.\n//\n// After changing users, the PostBecome function is called when configured.\n// This allows an application to for instance update state or other such\n// properties when the user changes.\n//\n// Use sparingly and after properly checking permissions to see if\n// the user is really supposed to be able to become that user.\nfunc (ctx *PfCtxS) Become(user PfUser) {\n\t// Use the details from the user\n\tctx.user = user",
"\t// Select one-self\n\tctx.sel_user = user",
"\t// Post Become() hook if configured\n\tif ctx.f_postbecome != nil {\n\t\tctx.f_postbecome(ctx)\n\t}\n}",
"// GetToken retrieves the authentication token (JWT) provided by the user, if any\nfunc (ctx *PfCtxS) GetToken() (tok string) {\n\treturn ctx.token\n}",
"// NewToken causes a new JWT websession token to be generated for loggedin users\nfunc (ctx *PfCtxS) NewToken() (err error) {\n\tif !ctx.IsLoggedIn() {\n\t\treturn errors.New(\"Not authenticated\")\n\t}",
"\ttheuser := ctx.TheUser()",
"\t// Set some claims\n\tctx.token_claims.UserDesc = theuser.GetFullName()\n\tctx.token_claims.IsSysAdmin = ctx.is_sysadmin",
"\tusername := theuser.GetUserName()",
"\t// Create the token\n\ttoken := Token_New(\"websession\", username, TOKEN_EXPIRATIONMINUTES, &ctx.token_claims)",
"\t// Sign and get the complete encoded token as a string\n\tctx.token, err = token.Sign()\n\tif err != nil {\n\t\t// Invalid token when something went wrong\n\t\tctx.token = \"\"\n\t}",
"\treturn\n}",
"// LoginToken can be used to log in using a token.\n//\n// It takes a JWT encoded as a string.\n// It returns a boolean indicating if the token is going to expire soon\n// (and thus indicating that a new token should be sent out to the user)\n// and/or an error to indicate failure.\nfunc (ctx *PfCtxS) LoginToken(tok string) (expsoon bool, err error) {\n\t// No valid token\n\tctx.token = \"\"",
"\t// Not a SysAdmin\n\tctx.is_sysadmin = false",
"\t// Parse the provided token\n\texpsoon, err = Token_Parse(tok, \"websession\", &ctx.token_claims)\n\tif err != nil {\n\t\treturn expsoon, err\n\t}",
"\t// Who they claim they are\n\tuser := ctx.NewUser()\n\tuser.SetUserName(ctx.token_claims.Subject)\n\tuser.SetFullName(ctx.token_claims.UserDesc)\n\tctx.is_sysadmin = ctx.token_claims.IsSysAdmin",
"\t// Fetch the details\n\terr = user.Refresh(ctx)\n\tif err == ErrNoRows {\n\t\tctx.Dbgf(\"No such user %q\", ctx.token_claims.Subject)\n\t\treturn false, errors.New(\"No such user\")\n\t} else if err != nil {\n\t\tctx.Dbgf(\"Fetch of user %q failed: %s\", ctx.token_claims.Subject, err.Error())\n\t\treturn false, err\n\t}",
"\t// Looking good, become the user\n\tctx.Become(user)",
"\t// Valid Token\n\tctx.token = tok",
"\treturn expsoon, nil\n}",
"// Login can be used to login using a username, password\n// and optionally, when configured, a twofactor code.\n//\n// A userevent is logged when this function was succesful.\nfunc (ctx *PfCtxS) Login(username string, password string, twofactor string) (err error) {\n\t// The new user */\n\tuser := ctx.NewUser()",
"\terr = user.CheckAuth(ctx, username, password, twofactor)\n\tif err != nil {\n\t\t/* Log the error, so that it can be looked up in the log */\n\t\tctx.Errf(\"CheckAuth(%s): %s\", username, err)",
"\t\t/* Overwrite the error so that we do not leak too much detail */\n\t\terr = ErrLoginIncorrect\n\t\treturn\n\t}",
"\t// Force generation of a new token\n\tctx.token = \"\"",
"\t// Not a sysadmin till they swapadmin\n\tctx.is_sysadmin = false",
"\tctx.Become(user)",
"\tuserevent(ctx, \"login\")\n\treturn nil\n}",
"// Logout can be used to log the authenticated user out of the system.\n//\n// The JWT token that was previously in use is added to the JWT Invalidated list\n// thus denying the further use of that token.\nfunc (ctx *PfCtxS) Logout() {\n\tif ctx.token != \"\" {\n\t\tJwt_invalidate(ctx.token, &ctx.token_claims)\n\t}",
"\t/* Invalidate user + token */\n\tctx.user = nil\n\tctx.token = \"\"\n\tctx.token_claims = SessionClaims{}\n}",
"// IsLoggedIn can be used to check if the context has a properly logged in user.\nfunc (ctx *PfCtxS) IsLoggedIn() bool {\n\tif ctx.user == nil {\n\t\treturn false\n\t}",
"\treturn true\n}",
"// IsGroupMember can be used to check if the selected user\n// is a member of the selected group and whether the user\n// can see the group.\nfunc (ctx *PfCtxS) IsGroupMember() bool {\n\tif !ctx.HasSelectedUser() {\n\t\treturn false\n\t}",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\tismember, _, state, err := ctx.sel_group.IsMember(ctx.user.GetUserName())\n\tif err != nil {\n\t\tctx.Log(\"IsGroupMember: \" + err.Error())\n\t\treturn false\n\t}",
"\tif !ismember {\n\t\treturn false\n\t}",
"\t/* Group Admins can always select users, even when blocked */\n\tif ctx.IAmGroupAdmin() {\n\t\treturn true\n\t}",
"\t/* Normal group users, it depends on whether they can see them */\n\treturn state.can_see\n}",
"// IAmGroupAdmin can be used to ask if the logged in user\n// is a groupadmin of the selected group.\nfunc (ctx *PfCtxS) IAmGroupAdmin() bool {\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\tif ctx.IsSysAdmin() {\n\t\treturn true\n\t}",
"\t_, isadmin, _, err := ctx.sel_group.IsMember(ctx.user.GetUserName())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn isadmin\n}",
"// IAmGroupMember can be used to check if the logged in user is a groupmember\nfunc (ctx *PfCtxS) IAmGroupMember() bool {\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\tismember, _, _, err := ctx.sel_group.IsMember(ctx.user.GetUserName())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn ismember\n}",
"// GroupHasWiki can be used to check if the selected group has a wiki module enabled\nfunc (ctx *PfCtxS) GroupHasWiki() bool {\n\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\treturn ctx.sel_group.HasWiki()\n}",
"// GroupHasFile can be used to check if the selected group has a file module enabled\nfunc (ctx *PfCtxS) GroupHasFile() bool {\n\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\treturn ctx.sel_group.HasFile()\n}",
"// GroupHasCalendar can be used to check if the selected group has a calendar module enabled\nfunc (ctx *PfCtxS) GroupHasCalendar() bool {\n\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\treturn ctx.sel_group.HasCalendar()\n}",
"// SwapSysAdmin swaps a user's privilege between normal user and sysadmin.\nfunc (ctx *PfCtxS) SwapSysAdmin() bool {\n\t/* Not logged, can't be SysAdmin */\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\t/* If they cannot be one, then do not toggle either */\n\tif !ctx.TheUser().CanBeSysAdmin() {\n\t\treturn false\n\t}",
"\t/* Toggle state: SysAdmin <> Regular */\n\tctx.is_sysadmin = !ctx.is_sysadmin",
"\t/* Force generation of a new token */\n\tctx.token = \"\"",
"\treturn true\n}",
"// IsSysAdmin indicates if the current user is a sysadmin\n// and has swapped to it, see SwapSysAdmin.\n//\n// The SAR (System Administation Restrictions) are checked.\n// When the SAR is enabled/configured, one can only become/be\n// a sysadmin when coming from the correct IP address as\n// configured in th SAR list.\nfunc (ctx *PfCtxS) IsSysAdmin() bool {\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\t/* Not a SysAdmin, easy */\n\tif !ctx.is_sysadmin {\n\t\treturn false\n\t}",
"\tsys := System_Get()",
"\t/*\n\t * SysAdmin IP Restriction in effect?\n\t *\n\t * Loopback (127.0.0.1 / ::1) are excluded from this restriction\n\t */\n\tif sys.sar_cache == nil || ctx.client_ip.IsLoopback() {\n\t\treturn true\n\t}",
"\t/* Check all the prefixes */\n\tfor _, n := range sys.sar_cache {\n\t\tif n.Contains(ctx.client_ip) {\n\t\t\t/* It is valid */\n\t\t\treturn true\n\t\t}\n\t}",
"\t/* Not in the SARestrict list */\n\treturn false\n}",
"// FromString can be used to parse a string into a Perm object.\n//\n// str can be in the formats:\n// perm1\n// perm1,perm2\n// perm1,perm2,perm3\n//\n// When an unknown permission is encountered, this function will return an error.",
"func (perm Perm) FromString(str string) (err error) {",
"\tstr = strings.ToLower(str)",
"\tperm = PERM_NOTHING",
"\tp := strings.Split(str, \",\")\n\tfor _, pm := range p {\n\t\tif pm == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\tfound := false\n\t\tvar i uint\n\t\ti = 0\n\t\tfor _, n := range permnames {\n\t\t\tif pm == n {\n\t\t\t\tperm += 1 << i\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}",
"\t\tif !found {\n\t\t\terr = errors.New(\"Unknown permission: '\" + pm + \"'\")\n\t\t\treturn\n\t\t}\n\t\tbreak\n\t}",
"\terr = nil\n\treturn\n}",
"// String returns the string representation of a Perm.\n//\n// This can be used for in for instance debug output.\nfunc (perm Perm) String() (str string) {",
"\tfor i := 0; i < len(permnames); i++ {\n\t\tp := uint64(math.Pow(float64(2), float64(i)))",
"\t\tif uint64(perm)&p == 0 {\n\t\t\tcontinue\n\t\t}",
"\t\tif str != \"\" {\n\t\t\tstr += \",\"\n\t\t}",
"\t\tstr += permnames[i]\n\t}",
"\treturn str\n}",
"/* IsPerm returns whether the provided Perm is the same Perm as given */\nfunc (perm Perm) IsPerm(perms Perm) bool {\n\treturn perms == perm\n}",
"/* IsSet checks if the perm is in the given set of Perms */\nfunc (perm Perm) IsSet(perms Perm) bool {\n\treturn perms&perm > 0\n}",
"// CheckPerms can verify if the given permissions string is valied for the provided Perms.\n//\n// One of multiple permissions can be specified by OR-ing the permissions together\n// thus test from least to most to see if any of them allows access.\n//\n// To debug permissions, toggle the code-level switch in PDbg and PDbgf().\n//\n// Application permissions are tested at the end when all pitchfork permissions\n// still allow it to proceed.\n//\n// The what parameter indicates the piece of code wanting to see the permissions\n// verified, this thus primarily serves as a debug help.\nfunc (ctx *PfCtxS) CheckPerms(what string, perms Perm) (ok bool, err error) {\n\t/* No error yet */\n\tsys := System_Get()",
"\tctx.PDbgf(what, perms, \"Text: %s\", perms.String())",
"\tif ctx.IsLoggedIn() {\n\t\tctx.PDbgf(what, perms, \"user = %s\", ctx.user.GetUserName())\n\t} else {\n\t\tctx.PDbgf(what, perms, \"user = ::NONE::\")\n\t}",
"\tif ctx.HasSelectedUser() {\n\t\tctx.PDbgf(what, perms, \"sel_user = %s\", ctx.sel_user.GetUserName())\n\t} else {\n\t\tctx.PDbgf(what, perms, \"sel_user = ::NONE::\")\n\t}",
"\tif ctx.HasSelectedGroup() {\n\t\tctx.PDbgf(what, perms, \"sel_group = %s\", ctx.sel_group.GetGroupName())\n\t} else {\n\t\tctx.PDbgf(what, perms, \"sel_group = ::NONE::\")\n\t}",
"\t/* Nobody? */\n\tif perms.IsSet(PERM_NOBODY) {\n\t\tctx.PDbgf(what, perms, \"Nobody\")\n\t\treturn false, errors.New(\"Nobody is allowed\")\n\t}",
"\t/* No permissions? */\n\tif perms.IsPerm(PERM_NOTHING) {\n\t\tctx.PDbgf(what, perms, \"Nothing\")\n\t\treturn true, nil\n\t}",
"\t/* CLI when enabled and user is authenticated */\n\tif perms.IsSet(PERM_CLI) {\n\t\tctx.PDbgf(what, perms, \"CLI\")\n\t\tif ctx.IsLoggedIn() && sys.CLIEnabled {\n\t\t\tctx.PDbgf(what, perms, \"CLI - Enabled\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"CLI is not enabled\")\n\t\t}\n\t}",
"\t/* Loopback calls can always access the API (for tcli) */\n\tif perms.IsSet(PERM_API) {\n\t\tctx.PDbgf(what, perms, \"API\")\n\t\tif sys.APIEnabled {\n\t\t\tctx.PDbgf(what, perms, \"API - Enabled\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"API is not enabled\")\n\t\t}\n\t}",
"\t/* Is OAuth enabled? */\n\tif perms.IsSet(PERM_OAUTH) {\n\t\tctx.PDbgf(what, perms, \"OAuth\")\n\t\tif sys.OAuthEnabled {\n\t\t\tctx.PDbgf(what, perms, \"OAuth - Enabled\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"OAuth is not enabled\")\n\t\t}\n\t}",
"\t/* Loopback? */\n\tif perms.IsSet(PERM_LOOPBACK) {\n\t\tctx.PDbgf(what, perms, \"Loopback\")\n\t\tif ctx.client_ip.IsLoopback() {\n\t\t\tctx.PDbgf(what, perms, \"Is Loopback\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"Not a Loopback\")\n\t\t}\n\t}",
"\t/* User must not be authenticated */\n\tif perms.IsSet(PERM_GUEST) {\n\t\tctx.PDbgf(what, perms, \"Guest\")\n\t\tif !ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"Guest - Not Logged In\")\n\t\t\treturn true, nil\n\t\t}",
"\t\tctx.PDbgf(what, perms, \"Guest - Logged In\")\n\t\treturn false, errors.New(\"Must not be authenticated\")\n\t}",
"\t/* User has to have selected themselves */\n\tif perms.IsSet(PERM_USER_SELF) {\n\t\tctx.PDbgf(what, perms, \"User Self\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User Self - Logged In\")\n\t\t\tif ctx.HasSelectedUser() {\n\t\t\t\tctx.PDbgf(what, perms, \"User Self - Has selected user\")\n\t\t\t\tif ctx.sel_user.GetUserName() == ctx.user.GetUserName() {\n\t\t\t\t\t/* Passed the test */\n\t\t\t\t\tctx.PDbgf(what, perms, \"User Self - It is me\")\n\t\t\t\t\treturn true, nil\n\t\t\t\t} else {\n\t\t\t\t\tctx.PDbgf(what, perms, \"User Self - Other user\")\n\t\t\t\t\terr = errors.New(\"Different user selected\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"No user selected\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* User has to have selected themselves */\n\tif perms.IsSet(PERM_USER_VIEW) {\n\t\tctx.PDbgf(what, perms, \"User View\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User View - Logged In\")\n\t\t\tif ctx.HasSelectedUser() {\n\t\t\t\tctx.PDbgf(what, perms, \"User View - Has selected user\")\n\t\t\t\tif ctx.sel_user.GetUserName() == ctx.user.GetUserName() {\n\t\t\t\t\t/* Passed the test */\n\t\t\t\t\tctx.PDbgf(what, perms, \"User View - It is me\")\n\t\t\t\t\treturn true, nil\n\t\t\t\t} else {\n\t\t\t\t\tok, err = ctx.sel_user.SharedGroups(ctx, ctx.user)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t/* Passed the test */\n\t\t\t\t\t\tctx.PDbgf(what, perms, \"User View - It is in my group\")\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t} else {\n\t\t\t\t\t\tctx.PDbgf(what, perms, \"User View - Other user\")\n\t\t\t\t\t\terr = errors.New(\"Different user selected\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"No user selected\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* User has to be a group member + Wiki enabled */\n\tif perms.IsSet(PERM_GROUP_WIKI) {\n\t\tctx.PDbgf(what, perms, \"Group Wiki?\")\n\t\tif ctx.GroupHasWiki() {\n\t\t\tctx.PDbgf(what, perms, \"HasWiki - ok\")\n\t\t\tif ctx.IsGroupMember() {\n\t\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\terr = errors.New(\"Not a group member\")\n\t\t} else {\n\t\t\terr = errors.New(\"Group does not have a Wiki\")\n\t\t\treturn false, err\n\t\t}\n\t}",
"\t/* User has to be a group member + File enabled */\n\tif perms.IsSet(PERM_GROUP_FILE) {\n\t\tctx.PDbgf(what, perms, \"Group File?\")\n\t\tif ctx.GroupHasFile() {\n\t\t\tctx.PDbgf(what, perms, \"HasFile - ok\")\n\t\t\tif ctx.IsGroupMember() {\n\t\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\terr = errors.New(\"Not a group member\")\n\t\t} else {\n\t\t\terr = errors.New(\"Group does not have a File\")\n\t\t\treturn false, err\n\t\t}\n\t}",
"\t/* User has to be a group member + Calendar enabled */\n\tif perms.IsSet(PERM_GROUP_CALENDAR) {\n\t\tctx.PDbgf(what, perms, \"Group Calendar?\")\n\t\tif ctx.GroupHasCalendar() {\n\t\t\tctx.PDbgf(what, perms, \"HasCalendar - ok\")\n\t\t\tif ctx.IsGroupMember() {\n\t\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\terr = errors.New(\"Not a group member\")\n\t\t} else {\n\t\t\terr = errors.New(\"Group does not have a Calendar\")\n\t\t\treturn false, err\n\t\t}\n\t}",
"\t/* No permissions needed */\n\tif perms.IsSet(PERM_NONE) {\n\t\tctx.PDbgf(what, perms, \"None\")\n\t\t/* Always succeeds */\n\t\treturn true, nil\n\t}",
"\t/* Everything else requires a login */\n\tif !ctx.IsLoggedIn() {\n\t\tctx.PDbgf(what, perms, \"Not Authenticated\")\n\t\terr = errors.New(\"Not authenticated\")\n\t\treturn false, err\n\t}",
"\t/*\n\t * SysAdmin can get away with almost anything\n\t *\n\t * The perms only has the PERM_SYS_ADMIN bit set for clarity\n\t * that that one only has access for sysadmins\n\t */\n\tif ctx.IsSysAdmin() {\n\t\tctx.PDbgf(what, perms, \"SysAdmin?\")\n\t\treturn true, nil\n\t}\n\terr = errors.New(\"Not a SysAdmin\")",
"\t/* User has to be authenticated */\n\tif perms.IsSet(PERM_USER) {\n\t\tctx.PDbgf(what, perms, \"User?\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User - Logged In\")\n\t\t\treturn true, nil\n\t\t}",
"\t\terr = errors.New(\"Not Authenticated\")\n\t}",
"\t/* User has to be a group admin */\n\tif perms.IsSet(PERM_GROUP_ADMIN) {\n\t\tctx.PDbgf(what, perms, \"Group admin?\")\n\t\tif ctx.IAmGroupAdmin() {\n\t\t\tctx.PDbgf(what, perms, \"Group admin - ok\")\n\t\t\treturn true, nil\n\t\t}",
"\t\terr = errors.New(\"Not a group admin\")\n\t}",
"\t/* User has to be a group member */\n\tif perms.IsSet(PERM_GROUP_MEMBER) {\n\t\tctx.PDbgf(what, perms, \"Group member?\")\n\t\tif ctx.IsGroupMember() {\n\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\treturn true, nil\n\t\t}",
"\t\terr = errors.New(\"Not a group member\")\n\t}",
"\t/* User wants to nominate somebody (even themselves) */\n\tif perms.IsSet(PERM_USER_NOMINATE) {\n\t\tctx.PDbgf(what, perms, \"User Nominate\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User Nominate - Logged In\")\n\t\t\tif ctx.HasSelectedUser() {\n\t\t\t\tctx.PDbgf(what, perms, \"User Nominate - User Selected\")\n\t\t\t\t/* Passed the test */\n\t\t\t\treturn true, nil\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"No user selected\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* Can the user become a SysAdmin? */\n\tif perms.IsSet(PERM_SYS_ADMIN_CAN) {\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"Sys Admin Can - Logged In\")\n\t\t\tif ctx.TheUser().CanBeSysAdmin() {\n\t\t\t\tctx.PDbgf(what, perms, \"Sys Admin Can\")\n\t\t\t\t/* Passed the test */\n\t\t\t\treturn true, nil\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"Can't become SysAdmin\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* Let the App Check permissions */\n\tif ctx.f_appperms != nil {\n\t\tfinal, _ok, _err := ctx.f_appperms(ctx, what, perms)\n\t\tif final {\n\t\t\treturn _ok, _err\n\t\t}",
"\t\t/* Otherwise we ignore the result as it is not a final decision */\n\t}",
"\tif err == nil {\n\t\t/* Should not happen */\n\t\tpanic(\"Invalid permission bits\")\n\t}",
"\t/* Default Deny + report error */\n\treturn false, err\n}",
"// CheckPermsT can be used to check a Textual version of permissions.\n//\n// Used when the caller has the textual representation of the permissions.\nfunc (ctx *PfCtxS) CheckPermsT(what string, permstr string) (ok bool, err error) {\n\tvar perms Perm\n",
"\terr = perms.FromString(permstr)",
"\tif err != nil {\n\t\treturn\n\t}",
"\treturn ctx.CheckPerms(what, perms)\n}",
"// TheUser returns the currently selected user\nfunc (ctx *PfCtxS) TheUser() (user PfUser) {\n\t/* Return a copy, not a reference */\n\treturn ctx.user\n}",
"// SelectedSelf checks if the logged in user and the selected user are the same.\nfunc (ctx *PfCtxS) SelectedSelf() bool {\n\treturn ctx.IsLoggedIn() &&\n\t\tctx.HasSelectedUser() &&\n\t\tctx.user.GetUserName() == ctx.sel_user.GetUserName()\n}",
"// SelectedUser returns the selected user.\nfunc (ctx *PfCtxS) SelectedUser() (user PfUser) {\n\t/* Return a copy, not a reference */\n\treturn ctx.sel_user\n}",
"// SelectedGroup returns the selected group.\nfunc (ctx *PfCtxS) SelectedGroup() (grp PfGroup) {\n\t/* Return a copy, not a reference */\n\treturn ctx.sel_group\n}",
"// SelectedML returns the selected mailinglist.\nfunc (ctx *PfCtxS) SelectedML() (ml PfML) {\n\t/* Return a copy, not a reference */\n\treturn *ctx.sel_ml\n}",
"// SelectedEmail returns the selected email address.\nfunc (ctx *PfCtxS) SelectedEmail() (email PfUserEmail) {\n\t/* Return a copy, not a reference */\n\treturn *ctx.sel_email\n}",
"// HasSelectedUser returns whether a user was selected.\nfunc (ctx *PfCtxS) HasSelectedUser() bool {\n\treturn ctx.sel_user != nil\n}",
"// HasSelectedGroup returns whether a group was selected.\nfunc (ctx *PfCtxS) HasSelectedGroup() bool {\n\treturn ctx.sel_group != nil\n}",
"// HasSelectedML returns whether a mailinglist was selected.\nfunc (ctx *PfCtxS) HasSelectedML() bool {\n\treturn ctx.sel_ml != nil\n}",
"// SelectMe caused the user to select themselves.\nfunc (ctx *PfCtxS) SelectMe() {\n\tctx.sel_user = ctx.user\n}",
"// SelectUser selects the user if the given permissions are matched.\nfunc (ctx *PfCtxS) SelectUser(username string, perms Perm) (err error) {\n\tctx.PDbgf(\"PfCtxS::SelectUser\", perms, \"%q\", username)",
"\t/* Nothing to select, always works */\n\tif username == \"\" {\n\t\tctx.sel_user = nil\n\t\treturn nil\n\t}",
"\t/* Selecting own user? */\n\ttheuser := ctx.TheUser()\n\tif theuser != nil && theuser.GetUserName() == username {\n\t\t/* Re-use and pass no username to indicate no refresh */\n\t\tctx.sel_user = theuser\n\t\tusername = \"\"\n\t} else {\n\t\tctx.sel_user = ctx.NewUser()\n\t}",
"\terr = ctx.sel_user.Select(ctx, username, perms)\n\tif err != nil {\n\t\tctx.sel_user = nil\n\t}",
"\treturn\n}",
"// SelectGroup selects the group, depending on the permission bits provided.\n//\n// After succesfully selecting, SelectedGroup can be used to retrieve the group.\nfunc (ctx *PfCtxS) SelectGroup(gr_name string, perms Perm) (err error) {\n\tctx.PDbgf(\"SelectGroup\", perms, \"%q\", gr_name)",
"\t/* Nothing to select */\n\tif gr_name == \"\" {\n\t\tctx.sel_group = nil\n\t\treturn nil\n\t}",
"\tctx.sel_group = ctx.NewGroup()\n\terr = ctx.sel_group.Select(ctx, gr_name, perms)\n\tif err != nil {\n\t\tctx.sel_group = nil\n\t}",
"\treturn\n}",
"// SelectML selects a mailinglist depending on the permissions of the logged in user\nfunc (ctx *PfCtxS) SelectML(ml_name string, perms Perm) (err error) {\n\tctx.PDbgf(\"SelectUserML\", perms, \"%q\", ml_name)",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn errors.New(\"No group selected\")\n\t}",
"\t/* Nothing to select */\n\tif ml_name == \"\" {\n\t\tctx.sel_ml = nil\n\t\treturn nil\n\t}",
"\tctx.sel_ml = NewPfML()\n\terr = ctx.sel_ml.Select(ctx, ctx.sel_group, ml_name, perms)",
"\tif err != nil {\n\t\tctx.sel_ml = nil\n\t}",
"\treturn\n}",
"// SelectEmail selects an email address.\n//\n// Users can only select their own email addresses (PERM_USER_SELF).\nfunc (ctx *PfCtxS) SelectEmail(email string) (err error) {\n\tperms := PERM_USER_SELF",
"\tctx.PDbgf(\"SelectEmail\", perms, \"%q\", email)",
"\t/* Nothing to select */\n\tif email == \"\" {\n\t\tctx.sel_email = nil\n\t\treturn nil\n\t}",
"\t/* Fetch email details */\n\tctx.sel_email = NewPfUserEmail()\n\terr = ctx.sel_email.Fetch(email)\n\tif err != nil {\n\t\t/* Did not work */\n\t\tctx.sel_email = nil\n\t\treturn\n\t}",
"\t/* Check Permissions */\n\tvar ok bool\n\tok, _ = ctx.CheckPerms(\"SelectEmail\", perms)\n\tif !ok {\n\t\t/* Nope, no access */\n\t\tctx.sel_email = nil\n\t}",
"\treturn\n}",
"// Err allows printing error messages (syslog/stdout) with details from the context.\nfunc (ctx *PfCtxS) Err(message string) {\n\tErrA(1, message)\n}",
"// Errf allows printing formatted error messages (syslog/stdout) with details from the context.\nfunc (ctx *PfCtxS) Errf(format string, a ...interface{}) {\n\tErrA(1, format, a...)\n}",
"// Log allows printing log messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Log(message string) {\n\tLogA(1, message)\n}",
"// Logf allows printing formatted log messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Logf(format string, a ...interface{}) {\n\tLogA(1, format, a...)\n}",
"// Dbg allows printing debug messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Dbg(message string) {\n\tDbgA(1, message)\n}",
"// Dbgf allows printing formatted debug messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Dbgf(format string, a ...interface{}) {\n\tDbgA(1, format, a...)\n}",
"// PDbgf is used for permission debugging.\n//\n// It needs to be enabled with a Code level Debug option.\n// Change the 'false' to 'true' and every permission decision will be listed.\n// Remember: sysadmin overrules most permissions, thus test with normal user.\nfunc (ctx *PfCtxS) PDbgf(what string, perm Perm, format string, a ...interface{}) {\n\tif false {\n\t\tctx.Dbgf(\"Perms(\\\"\"+what+\"\\\"/\"+strconv.Itoa(int(perm))+\"): \"+format, a...)\n\t}\n}",
"// Out can be used to print a line to the output for the context (CLI or HTTP).\n//\n// When buffering is disabled, the txt is directly forwarded to a special\n// direct output function.\n//\n// When buffering is enabled, the txt is accumulatd in the output buffer.\nfunc (ctx *PfCtxS) Out(txt string) {\n\tif !ctx.mode_buffered {\n\t\t/* Call the function that takes care of Direct output */\n\t\t_, err := ObjFunc(ctx.outunbuf_obj, ctx.outunbuf_fun, txt)\n\t\tif err != nil {\n\t\t\tctx.Errf(\"Unbuffered output failed: %s\", err.Error())\n\t\t}\n\t} else {\n\t\t/* Buffered output */\n\t\tctx.output += txt\n\t}\n}",
"// Outf can be used to let the Out string be formatted first.\nfunc (ctx *PfCtxS) Outf(format string, a ...interface{}) {\n\tctx.Out(fmt.Sprintf(format, a...))\n}",
"// OutLn ensure that the Out outputted message ends in a newline\nfunc (ctx *PfCtxS) OutLn(format string, a ...interface{}) {\n\tctx.Outf(format+\"\\n\", a...)\n}",
"// SetOutUnbuffered causes the Out* functions to become unbuffered.\n//\n// The object and function passed in are then later used for calling\n// and acually performing the output of the txt with the Out() function.\nfunc (ctx *PfCtxS) SetOutUnbuffered(obj interface{}, fun string) {\n\tobjtrail := []interface{}{obj}\n\tok, obji := ObjHasFunc(objtrail, fun)\n\tif !ok {\n\t\tpanic(\"Unbuffered function \" + fun + \" is missing\")\n\t}",
"\tctx.outunbuf_obj = obji\n\tctx.outunbuf_fun = fun\n}",
"// OutBuffered causes the Out* functions to become buffered.\nfunc (ctx *PfCtxS) OutBuffered(on bool) {\n\tif !on && ctx.outunbuf_fun == \"\" {\n\t\tpanic(\"Can't enable buffered mode without unbuffered function\")\n\t}",
"\tctx.mode_buffered = on\n}",
"// IsBuffered can be used to check if output is being buffered or directly outputted.\nfunc (ctx *PfCtxS) IsBuffered() bool {\n\treturn ctx.mode_buffered\n}",
"// Buffered can be used to return the buffered string.\nfunc (ctx *PfCtxS) Buffered() (o string) {\n\to = ctx.output\n\tctx.output = \"\"\n\treturn\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,
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,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1336, 1537], "buggy_code_start_loc": [947, 1355], "filenames": ["lib/ctx.go", "lib/struct.go"], "fixing_code_end_loc": [1336, 1538], "fixing_code_start_loc": [947, 1356], "message": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:secluded:trident:1.4.6:rc1:*:*:*:*:*:*", "matchCriteriaId": "52F21E24-C1E2-4E41-B00C-FB5441CCD7CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2."}, {"lang": "es", "value": "Pitchfork, en su versi\u00f3n 1.4.6 RC1, contiene una vulnerabilidad de gesti\u00f3n incorrecta de privilegios en los componentes Trident Pitchfork que puede resultar en que un usuario est\u00e1ndar sin privilegios obtenga permisos de administrador en el portal web. El usuario debe ser capaz de iniciar sesi\u00f3n y podr\u00eda editar su perfil y establecer el permiso \"System Administrator\" en \"yes\" para s\u00ed mismo. La vulnerabilidad parece haber sido solucionada en la versi\u00f3n 1.4.6 RC2."}], "evaluatorComment": null, "id": "CVE-2018-1000133", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-03-16T14:29:44.847", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/9fd07cbe4f93e1367e142016e9a205366680dd54"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/issues/168"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/tridentli/trident/releases/tag/DEV_1.4.6-RC2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://thomas-ward.net/security-advisories/trident-trusted-communications-platform-privilege-escalation-issue-advisory/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-269"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, "type": "CWE-269"}
| 312
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"// Pitchfork ctx defines the context that is passed through Pitchfork pertaining primarily to the logged in, selected user/group\npackage pitchfork",
"import (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"",
"\tuseragent \"github.com/mssola/user_agent\"\n\ti18n \"github.com/nicksnyder/go-i18n/i18n\"\n)",
"// ErrLoginIncorrect is used when a login is incorrect, this to hide more specific reasons\nvar ErrLoginIncorrect = errors.New(\"Login incorrect\")",
"// PfNewUserI, NewGroupI, PfMenuI, PfAppPermsI, PfPostBecomeI are function definitions to allow overriding of these functions by application code\ntype PfNewUserI func() (user PfUser)\ntype PfNewGroupI func() (user PfGroup)\ntype PfMenuI func(ctx PfCtx, menu *PfMenu)\ntype PfAppPermsI func(ctx PfCtx, what string, perms Perm) (final bool, ok bool, err error)\ntype PfPostBecomeI func(ctx PfCtx)",
"// PfModOptsI is the interface that is implemented by PfModOptsS allowing the latter to be extended with more details\ntype PfModOptsI interface {\n\tIsModOpts() bool\n}",
"// PfModOptsS is the base structure used to impleent PfModOptsI\ntype PfModOptsS struct {\n\t// CLI command prefix, eg 'group wiki'\n\tCmdpfx string",
"\t// URL prefix, typically System_Get().PublicURL()\n\tURLpfx string",
"\t// Path Root\n\tPathroot string",
"\t// URL root, inside the hostname, eg '/group/name/wiki/'\n\tURLroot string\n}",
"// IsModOpts is a simple fakeish function to cause PfModOptsS to be of type PfModOptsI\n// as it requires this function to be present, which other structures will not satisfy.\nfunc (m PfModOptsS) IsModOpts() bool {\n\treturn true\n}",
"// PfModOpts can be used to easily initialize a PfModOptsS.\n//\n// The arguments match the variables in the PfModOpts structure.\n//\n// The function ensures that the web_root ends in a slash ('/').\nfunc PfModOpts(ctx PfCtx, cmdpfx string, path_root string, web_root string) PfModOptsS {\n\turlpfx := System_Get().PublicURL",
"\tweb_root = URL_EnsureSlash(web_root)",
"\treturn PfModOptsS{cmdpfx, urlpfx, path_root, web_root}\n}",
"// PfCtx is the Context Interface.\n//\n// PfCtxS is the default implementation.\n//\n// This interface is primarily intended to allow extension by an application.",
"// See the individual functions in PfCtxS for per function details.\ntype PfCtx interface {\n\tGetAbort() <-chan bool\n\tSetAbort(abort <-chan bool)\n\tSetTx(tx *Tx)\n\tGetTx() (tx *Tx)\n\tErr(message string)\n\tErrf(format string, a ...interface{})\n\tLog(message string)\n\tLogf(format string, a ...interface{})\n\tDbg(message string)\n\tDbgf(format string, a ...interface{})\n\tInit() (err error)\n\tSetStatus(code int)\n\tGetStatus() (code int)\n\tSetReturnCode(rc int)\n\tGetReturnCode() (rc int)\n\tGetLoc() string\n\tGetLastPart() string\n\tBecome(user PfUser)\n\tGetToken() (tok string)\n\tNewToken() (err error)\n\tLoginToken(tok string) (expsoon bool, err error)\n\tLogin(username string, password string, twofactor string) (err error)\n\tLogout()\n\tIsLoggedIn() bool\n\tIsGroupMember() bool\n\tIAmGroupAdmin() bool\n\tIAmGroupMember() bool\n\tGroupHasWiki() bool\n\tGroupHasFile() bool\n\tGroupHasCalendar() bool\n\tSwapSysAdmin() bool\n\tIsSysAdmin() bool\n\tCheckPerms(what string, perms Perm) (ok bool, err error)\n\tCheckPermsT(what string, permstr string) (ok bool, err error)\n\tTheUser() (user PfUser)\n\tSelectedSelf() bool\n\tSelectedUser() (user PfUser)\n\tSelectedGroup() (grp PfGroup)\n\tSelectedML() (ml PfML)\n\tSelectedEmail() (email PfUserEmail)\n\tHasSelectedUser() bool\n\tHasSelectedGroup() bool\n\tHasSelectedML() bool\n\tSelectMe()\n\tSelectUser(username string, perms Perm) (err error)\n\tSelectGroup(gr_name string, perms Perm) (err error)\n\tSelectML(ml_name string, perms Perm) (err error)\n\tSelectEmail(email string) (err error)\n\tSetModOpts(opts PfModOptsI)\n\tGetModOpts() (opts interface{})\n\tPDbgf(what string, perm Perm, format string, a ...interface{})\n\tOut(txt string)\n\tOutf(format string, a ...interface{})\n\tOutLn(format string, a ...interface{})\n\tSetOutUnbuffered(obj interface{}, fun string)\n\tOutBuffered(on bool)\n\tIsBuffered() bool\n\tBuffered() (o string)\n\tGetRemote() (remote string)\n\tSetClient(clientip net.IP, remote string, ua string)\n\tGetClientIP() net.IP\n\tGetUserAgent() (string, string, string)\n\tSelectObject(obj *interface{})\n\tSelectedObject() (obj *interface{})\n\tGetLanguage() string\n\tSetLanguage(name string)\n\tGetTfunc() i18n.TranslateFunc",
"\t// User and Group creation overrides\n\tNewUser() (user PfUser)\n\tNewUserI() (i interface{})\n\tNewGroup() (user PfGroup)\n\tNewGroupI() (i interface{})",
"\t// Menu Overrides\n\tMenuOverride(menu *PfMenu)",
"\t// Menu Related (menu.go)\n\tMenu(args []string, menu PfMenu) (err error)\n\tWalkMenu(args []string) (menu *PfMEntry, err error)\n\tCmd(args []string) (err error)\n\tCmdOut(cmd string, args []string) (msg string, err error)\n\tBatch(filename string) (err error)",
"\t// Application Data\n\tSetAppData(data interface{})\n\tGetAppData() interface{}\n}",
"// SessionClaims describe claims for a session\ntype SessionClaims struct {\n\tJWTClaims\n\tUserDesc string `json:\"userdesc\"`\n\tIsSysAdmin bool `json:\"issysadmin\"`\n}",
"// PfCtxS is the default implementation of PfCtx\ntype PfCtxS struct {\n\tabort <-chan bool /* Abort the request */\n\tstatus int /* HTTP Status code */\n\treturncode int /* Command Line return code */\n\tloc string /* Command tree location */\n\toutput string /* Output buffer */\n\tmode_buffered bool /* Buffering of output in effect */\n\tuser PfUser /* Authenticated User */\n\tis_sysadmin bool /* Whether the user's sysadmin priveleges are enabled */\n\ttoken string /* The authentication token */\n\ttoken_claims SessionClaims /* Parsed Token Claims */\n\tremote string /* The address of the client, including X-Forwarded-For */\n\tclient_ip net.IP /* Client's IP addresses */\n\tua_full string /* The HTTP User Agent */\n\tua_browser string /* HTTP User Agent: Browser */\n\tua_os string /* HTTP User Agent: Operating System */\n\tlanguage string /* User's chosen language (TODO: Allow user to select it) */\n\ttfunc i18n.TranslateFunc /* Translation function populated with current language */\n\tsel_user PfUser /* Selected User */\n\tsel_group PfGroup /* Selected Group */\n\tsel_ml *PfML /* Selected Mailing List */\n\tsel_email *PfUserEmail /* Selected User email address */\n\tsel_obj *interface{} /* Selected Object (ctx + struct only) */\n\tmod_opts interface{} /* Module Options for Messages/Wiki/Files etc */\n\tf_newuser PfNewUserI /* Create a new User */\n\tf_newgroup PfNewGroupI /* Create a new Group */\n\tf_menuoverride PfMenuI /* Override a menu */\n\tf_appperms PfAppPermsI /* Application Permission Check */\n\tf_postbecome PfPostBecomeI /* Post Become() */",
"\t// Unbuffered Output */\n\toutunbuf_fun string // Function name that handles unbuffered output */\n\toutunbuf_obj ObjFuncI // Object where the function lives */",
"\t// Database internal\n\tdb_Tx *Tx // Used for database transactions",
"\t// Menu internal values (menu.go)\n\tmenu_walkonly bool // Set to 'true' to indicate that only walk, do not execute; used for figuring out what arguments are needed\n\tmenu_args []string // Which arguments are currently requested\n\tmenu_menu *PfMEntry // Current menu entry being attempted",
"\t/* Application Data */\n\tappdata interface{} // Application specific data\n}",
"// PfNewCtx allows overriding the NewCtx function, thus allowing extending PfCtx\ntype PfNewCtx func() PfCtx",
"// NewPfCtx is used to initialize a new Pitchfork Context.\n//\n// The various arguments are all to provide the ability to replace\n// standard Pitchfork functions with application specific ones that\n// likely extends the Pitchfork functionality or that carry extra details.\n//\n// newuser is used as a function for creating new users.\n//\n// newgroup is used as a function for creating new groups.\n//\n// menuoverride is used as a function to override menu entries.\n//\n// appperms is used as a function to verify application specific permissions.\n//\n// postbecome is used as a callback after a user has changed (eg when logging in).\n//\n// All overrides are optional, and will be defaulted to the Pitchfork versions\n// when they are provided as 'nil'.\n//\n// NewPfCtx is called from the constructors of PfUI and, except for testing\n// should rarely be called directly as the context is already handed to a function.\nfunc NewPfCtx(newuser PfNewUserI, newgroup PfNewGroupI, menuoverride PfMenuI, appperms PfAppPermsI, postbecome PfPostBecomeI) PfCtx {\n\tif newuser == nil {\n\t\tnewuser = NewPfUserA\n\t}",
"\tif newgroup == nil {\n\t\tnewgroup = NewPfGroup\n\t}",
"\ttfunc, err := i18n.Tfunc(Config.TransDefault)\n\tif err != nil {\n\t\ttfunc = nil\n\t}",
"\treturn &PfCtxS{f_newuser: newuser,\n\t\tf_newgroup: newgroup, f_menuoverride: menuoverride, f_appperms: appperms,\n\t\tf_postbecome: postbecome,\n\t\tlanguage: Config.TransDefault, mode_buffered: true, tfunc: tfunc}\n}",
"// GetAbort is used to retrieve the abort channel (as used/passed-down from the HTTP handler)\n//\n// This channel is used to indicate, by the HTTP library, that the HTTP client has\n// disconnected and that the request can be aborted as the client will never receive\n// the answer of the query.\n//\n// Used amongst others by the search infrastructure.\nfunc (ctx *PfCtxS) GetAbort() <-chan bool {\n\treturn ctx.abort\n}",
"// SetAbort is used to set the abort channel (as used/passed-down from the HTTP handler).\n//\n// SetAbort is called from H_root() to configure the abort channel as passed down\n// from the Golang HTTP package.\nfunc (ctx *PfCtxS) SetAbort(abort <-chan bool) {\n\tctx.abort = abort\n}",
"// GetLanguage is used to retrieve the user-selected language setting\n//\n// The returned string is in the form of a RFC2616 Accept-Language header.\n// Typically it will be 'en-us', or sometimes 'de', 'de-DE', 'de-CH' or 'es'.\nfunc (ctx *PfCtxS) GetLanguage() string {\n\treturn ctx.language\n}",
"// SetLanguage accepts a RFC2616 style Accept-Language string\n// it then uses that information to determine the best language\n// to return.\nfunc (ctx *PfCtxS) SetLanguage(name string) {\n\tctx.language = name\n\ttfunc, err := i18n.Tfunc(name, Config.TransDefault)\n\tif err != nil {\n\t\t// XXX: Handle properly, this crashes the goproc based on invalid Accept-Language header\n\t\t// The panic might expose information to the enduser\n\t\tpanic(err.Error())\n\t}\n\tctx.tfunc = tfunc\n}",
"// GetTfunc returns the translation function\nfunc (ctx *PfCtxS) GetTfunc() i18n.TranslateFunc {\n\treturn ctx.tfunc\n}",
"// SetAppData can be used to set the appdata of a context.\n//\n// Typically this is used by an application's edition of a context to store\n// itself in the pitchfork context. This given that Golang does not support\n// polymorphism and thus needs a place to hide the full version of itself.\nfunc (ctx *PfCtxS) SetAppData(appdata interface{}) {\n\tctx.appdata = appdata\n}",
"// GetAppData is used for getting application specific data inside the context.\n//\n// Typically this is used by an application's edition of a context to retrieve\n// itself from the pitchfork context. This given that Golang does not support\n// polymorphism and it needs to retrieve itself from the embedded edition of itself.\nfunc (ctx *PfCtxS) GetAppData() interface{} {\n\treturn ctx.appdata\n}",
"// NewUser causes a new PfUser (or extended edition) to be created.\n//\n// The override for NewUser, as configured at Ctx creation time is used\n// thus allowing the application specific Ctx to be returned.\nfunc (ctx *PfCtxS) NewUser() PfUser {\n\treturn ctx.f_newuser()\n}",
"// NewUserI is like NewUser() but returns a generic interface */\nfunc (ctx *PfCtxS) NewUserI() interface{} {\n\treturn ctx.f_newuser()\n}",
"// NewGroup causes a new PfGroup to be created by calling the\n// application defined edition of a NewGroup function.\nfunc (ctx *PfCtxS) NewGroup() PfGroup {\n\treturn ctx.f_newgroup()\n}",
"// NewGroupI is like NewGroup() but returns a generic interface\nfunc (ctx *PfCtxS) NewGroupI() interface{} {\n\treturn ctx.f_newgroup()\n}",
"// MenuOverride is called before a menu is further processed,\n// allowing entries to be modified by calling the callback.\n//\n// As noted, it is an optional override.\nfunc (ctx *PfCtxS) MenuOverride(menu *PfMenu) {\n\tif ctx.f_menuoverride != nil {\n\t\tctx.f_menuoverride(ctx, menu)\n\t}\n}",
"// SetTx is used by the database code to select the current transaction\nfunc (ctx *PfCtxS) SetTx(tx *Tx) {\n\tctx.db_Tx = tx\n}",
"// GetTx is used by the database code to get the current transaction\nfunc (ctx *PfCtxS) GetTx() (tx *Tx) {\n\treturn ctx.db_Tx\n}",
"// GetRemote retrieves the remote address of the user/connection.\n//\n// The address is a IPv4 or IPv6 textual representation.\nfunc (ctx *PfCtxS) GetRemote() (remote string) {\n\treturn ctx.remote\n}",
"// SetClient is used for configuring the client IP, remote address and Full User Agent strings.\n//\n// Typically not called from an application, but from cui's SetClientIP()\n// which in turn gets called from the H_root.\n//\n// The clientip is a pre-parsed IP address and XFF-filtered hops.\n//\n// Remote contains the full IP address string (including X-Forwarded-For hops).\n//\n// Fullua contains the HTTP User-Agent header.\n//\n// This function sets the variables of the Ctx (client_ip, remote) and parses\n// the Fullua (Full User-Agent) variable, storing the details in Ctx.\nfunc (ctx *PfCtxS) SetClient(clientip net.IP, remote string, fullua string) {\n\tctx.client_ip = clientip\n\tctx.remote = remote",
"\t/* Split the UA in several parts */\n\tua := useragent.New(fullua)\n\tctx.ua_full = fullua\n\tif ua != nil {\n\t\tctx.ua_browser, _ = ua.Browser()\n\t\tctx.ua_os = ua.OS()\n\t} else {\n\t\t/* Did not parse as it is the CLI */\n\t\tif clientip.IsLoopback() {\n\t\t\tctx.ua_browser = \"Tickly\"\n\t\t\tctx.ua_os = \"Trident\"\n\t\t} else {\n\t\t\tctx.ua_browser = \"unknown\"\n\t\t\tctx.ua_os = \"unknown\"\n\t\t}\n\t}\n}",
"// GetClientIP is used to get the client's IP address\nfunc (ctx *PfCtxS) GetClientIP() net.IP {\n\treturn ctx.client_ip\n}",
"// GetUserAgent is used for retrieving the parsed User Agent; see also SetClient()\nfunc (ctx *PfCtxS) GetUserAgent() (string, string, string) {\n\treturn ctx.ua_full, ctx.ua_browser, ctx.ua_os\n}",
"// SelectObject is used by the struct code (lib/struct.go) to set the\n// object that it wants to keep track of during parsing.\nfunc (ctx *PfCtxS) SelectObject(obj *interface{}) {\n\tctx.sel_obj = obj\n}",
"// SelectedObject is used by the struct code to retrieve\n// the object it is currently parsing.\nfunc (ctx *PfCtxS) SelectedObject() (obj *interface{}) {\n\treturn ctx.sel_obj\n}",
"// SetModOpts allows setting the options for the wiki and file modules\nfunc (ctx *PfCtxS) SetModOpts(opts PfModOptsI) {\n\tctx.mod_opts = opts\n}",
"// GetModOpts allows getting the options for the wiki and file modules\nfunc (ctx *PfCtxS) GetModOpts() (opts interface{}) {\n\treturn ctx.mod_opts\n}",
"// Perm is used for storing the OR value of permissions\n//\n// Note: Keep in sync with permnames && ui/ui (convenience for all the menus there).\n//\n// It is used as a bitfield, hence multiple perms are possible by ORing them together.\n// Check access using the CheckPerms() function.\n//\n// The perms use the context's sel_{user|group|ml|*} variables to check if those permissions match.\n//\n// Being a SysAdmin overrides almost all permissions!\n//\n// Change the 'false' in PDbg to 'true' to see what permission decisions are being made.\n//\n// Application permissions are fully handled by the application.\n// See the CheckPerms function for more details.\ntype Perm uint64",
"// PERM_* define the permissions in the system.\n//\n// Each permission tests as true when the given condition is met.\n// See the per permission desciption for what condition they test for.\n//\n// The permissions are listed from weak (NONE) to strong (NOBODY).\n//\n// Permissions can be ORed together, the strongest are tested first.\n//\n// Not all combinations will make sense. eg combining PERM_GUEST|PERM_USER\n// means that both not-loggedin and loggedin users have access, at which\n// point the check can just be replaced with PERM_NONE.\n//\n// Application permissions our application specific.\n//\n// The PERM_'s marked 'Flag' are not used for checking permissions\n// but used for modifying the behavior of a menu entry.",
"const (\n\tPERM_NOTHING Perm = 0 // Nothing / empty permissions, primarily used for initialization, should not be found in code as it indicates that the Permission was not configured and thus should normally not be used\n\tPERM_NONE Perm = 1 << iota // No permissions needed (authenticated or unauthenticated is okay), typically combined with the a Flag like PERM_HIDDEN or PERM_NOSUBS\n\tPERM_GUEST // Tests that the user is not authenticated: The user is a Guest of the system; does not accept authenticated sessions\n\tPERM_USER // Tests that the user is logged in: the user has authenticated\n\tPERM_USER_SELF // Tests that the selected user matches the logged in user\n\tPERM_USER_NOMINATE // Tests that the user can nominate the selected user\n\tPERM_USER_VIEW // Tests that the user can view the selected user\n\tPERM_GROUP_MEMBER // Tests that the selected user is an active member of the selected group that can see the group\n\tPERM_GROUP_ADMIN // Tests that the selected user is an Admin of the selected group\n\tPERM_GROUP_WIKI // Tests that the selected Group has the Wiki section enabled\n\tPERM_GROUP_FILE // Tests that the selected Group has the File section enabled\n\tPERM_GROUP_CALENDAR // Tests that the selected Group has the Calendar section enabled\n\tPERM_SYS_ADMIN // Tests that the user is a System Administrator\n\tPERM_SYS_ADMIN_CAN // Can be a System Administrator\n\tPERM_CLI // Tests when the CLI option is enabled in system settings\n\tPERM_API // Tests when the API option is enabled in system settings\n\tPERM_OAUTH // Tests when the OAUTH option is enabled in system settings\n\tPERM_LOOPBACK // Tests that the connection comes from loopback (127.0.0.1 / ::1 as the Client/Remote IP address)\n\tPERM_HIDDEN // Flag: The menu option is hidden\n\tPERM_NOCRUMB // Flag: Don't add a crumb for this menu\n\tPERM_NOSUBS // Flag: No sub menus for this menu entry. See the NoSubs function for more details.\n\tPERM_NOBODY // Absolutely nobody has access (highest priority, first checked)",
"\t// Application permissions - defined by the application\n\tPERM_APP_0\n\tPERM_APP_1\n\tPERM_APP_2\n\tPERM_APP_3\n\tPERM_APP_4\n\tPERM_APP_5\n\tPERM_APP_6\n\tPERM_APP_7\n\tPERM_APP_8\n\tPERM_APP_9\n)",
"// permnames contains the human readable names matching the permissions\nvar permnames []string",
"// init is used to initialize permnames and verify that they are correct, at least in count\nfunc init() {\n\tpermnames = []string{\n\t\t\"nothing\",\n\t\t\"none\",\n\t\t\"guest\",\n\t\t\"user\",\n\t\t\"self\",\n\t\t\"user_nominate\",\n\t\t\"user_view\",\n\t\t\"group_member\",\n\t\t\"group_admin\",\n\t\t\"group_wiki\",\n\t\t\"group_file\",\n\t\t\"group_calendar\",\n\t\t\"sysadmin\",\n\t\t\"sysadmin_can\",\n\t\t\"cli\",\n\t\t\"api\",\n\t\t\"oauth\",\n\t\t\"loopback\",\n\t\t\"hidden\",\n\t\t\"nocrumb\",\n\t\t\"nosubs\",\n\t\t\"nobody\",\n\t\t\"app_0\",\n\t\t\"app_1\",\n\t\t\"app_2\",\n\t\t\"app_3\",\n\t\t\"app_4\",\n\t\t\"app_5\",\n\t\t\"app_6\",\n\t\t\"app_7\",\n\t\t\"app_9\",\n\t}",
"\t// Verify that the correct amount of permissions is present\n\tmax := uint64(1 << uint64(len(permnames)))\n\tif max != uint64(PERM_APP_9) {\n\t\tfmt.Printf(\"Expected %d got %d\\n\", max, PERM_APP_9)\n\t\tpanic(\"Invalid permnames\")\n\t}\n}",
"// Shortcutted commonly used HTTP error codes\nconst (\n\tStatusOK = 200\n\tStatusUnauthorized = 401\n)",
"// Debug is a Global Debug flag, used primarily for determining if debug messages should be output. Typically toggled by flags\nvar Debug = false",
"// Init is the \"constructor\" for Pitchfork Contexts\nfunc (ctx *PfCtxS) Init() (err error) {\n\t// Default HTTP status\n\tctx.status = StatusOK",
"\t// Default Shell Return Code to 0\n\tctx.returncode = 0",
"\treturn err\n}",
"// SetStatus can be used by a h_* function to set the status of the context.\n//\n// The status typically matches a HTTP error (eg StatusNotFound from golang HTTP library).\n//\n// The final status is flushed out during UI's Flush() time.\n//\n// The status code is tracked in lib instead of the UI layer to allow a generic\n// status code system inside Pitchfork.\nfunc (ctx *PfCtxS) SetStatus(code int) {\n\tctx.status = code\n}",
"// GetStatus can be used to get the status of the context.\n//\n// Typically only called by UI Flush(), but in theory could be used\n// by an application/function to check the current error code too.\nfunc (ctx *PfCtxS) GetStatus() (code int) {\n\treturn ctx.status\n}",
"// SetReturnCode is used by the CLI edition of tools to return a Shell Return Code.\nfunc (ctx *PfCtxS) SetReturnCode(rc int) {\n\tctx.returncode = rc\n}",
"// GetReturnCode is used by the CLI edition of tools to fetch the set Shell Return Code.\n//\n// During UI Flush() this error code is fetched and when not-0 reported as X-ReturnCode.\nfunc (ctx *PfCtxS) GetReturnCode() (rc int) {\n\treturn ctx.returncode\n}",
"// GetLoc returns where in the CLI menu system our code is located (XXX: Improve naming).\n//\n// This function is typically called by MenuOverrides so that they can determine\n// where they are and thus what they might want to change.\nfunc (ctx *PfCtxS) GetLoc() string {\n\treturn ctx.loc\n}",
"// GetLastPart is used to get the last portion of the location (XXX: Improve naming).\nfunc (ctx *PfCtxS) GetLastPart() string {\n\tfa := strings.Split(ctx.loc, \" \")\n\treturn fa[len(fa)-1]\n}",
"// Become can be used to become the given user.\n//\n// The context code that logs in a user uses this.\n// This can be used for a 'sudo' type mechanism as is cmd/setup/sudo.go.\n//\n// After changing users, the PostBecome function is called when configured.\n// This allows an application to for instance update state or other such\n// properties when the user changes.\n//\n// Use sparingly and after properly checking permissions to see if\n// the user is really supposed to be able to become that user.\nfunc (ctx *PfCtxS) Become(user PfUser) {\n\t// Use the details from the user\n\tctx.user = user",
"\t// Select one-self\n\tctx.sel_user = user",
"\t// Post Become() hook if configured\n\tif ctx.f_postbecome != nil {\n\t\tctx.f_postbecome(ctx)\n\t}\n}",
"// GetToken retrieves the authentication token (JWT) provided by the user, if any\nfunc (ctx *PfCtxS) GetToken() (tok string) {\n\treturn ctx.token\n}",
"// NewToken causes a new JWT websession token to be generated for loggedin users\nfunc (ctx *PfCtxS) NewToken() (err error) {\n\tif !ctx.IsLoggedIn() {\n\t\treturn errors.New(\"Not authenticated\")\n\t}",
"\ttheuser := ctx.TheUser()",
"\t// Set some claims\n\tctx.token_claims.UserDesc = theuser.GetFullName()\n\tctx.token_claims.IsSysAdmin = ctx.is_sysadmin",
"\tusername := theuser.GetUserName()",
"\t// Create the token\n\ttoken := Token_New(\"websession\", username, TOKEN_EXPIRATIONMINUTES, &ctx.token_claims)",
"\t// Sign and get the complete encoded token as a string\n\tctx.token, err = token.Sign()\n\tif err != nil {\n\t\t// Invalid token when something went wrong\n\t\tctx.token = \"\"\n\t}",
"\treturn\n}",
"// LoginToken can be used to log in using a token.\n//\n// It takes a JWT encoded as a string.\n// It returns a boolean indicating if the token is going to expire soon\n// (and thus indicating that a new token should be sent out to the user)\n// and/or an error to indicate failure.\nfunc (ctx *PfCtxS) LoginToken(tok string) (expsoon bool, err error) {\n\t// No valid token\n\tctx.token = \"\"",
"\t// Not a SysAdmin\n\tctx.is_sysadmin = false",
"\t// Parse the provided token\n\texpsoon, err = Token_Parse(tok, \"websession\", &ctx.token_claims)\n\tif err != nil {\n\t\treturn expsoon, err\n\t}",
"\t// Who they claim they are\n\tuser := ctx.NewUser()\n\tuser.SetUserName(ctx.token_claims.Subject)\n\tuser.SetFullName(ctx.token_claims.UserDesc)\n\tctx.is_sysadmin = ctx.token_claims.IsSysAdmin",
"\t// Fetch the details\n\terr = user.Refresh(ctx)\n\tif err == ErrNoRows {\n\t\tctx.Dbgf(\"No such user %q\", ctx.token_claims.Subject)\n\t\treturn false, errors.New(\"No such user\")\n\t} else if err != nil {\n\t\tctx.Dbgf(\"Fetch of user %q failed: %s\", ctx.token_claims.Subject, err.Error())\n\t\treturn false, err\n\t}",
"\t// Looking good, become the user\n\tctx.Become(user)",
"\t// Valid Token\n\tctx.token = tok",
"\treturn expsoon, nil\n}",
"// Login can be used to login using a username, password\n// and optionally, when configured, a twofactor code.\n//\n// A userevent is logged when this function was succesful.\nfunc (ctx *PfCtxS) Login(username string, password string, twofactor string) (err error) {\n\t// The new user */\n\tuser := ctx.NewUser()",
"\terr = user.CheckAuth(ctx, username, password, twofactor)\n\tif err != nil {\n\t\t/* Log the error, so that it can be looked up in the log */\n\t\tctx.Errf(\"CheckAuth(%s): %s\", username, err)",
"\t\t/* Overwrite the error so that we do not leak too much detail */\n\t\terr = ErrLoginIncorrect\n\t\treturn\n\t}",
"\t// Force generation of a new token\n\tctx.token = \"\"",
"\t// Not a sysadmin till they swapadmin\n\tctx.is_sysadmin = false",
"\tctx.Become(user)",
"\tuserevent(ctx, \"login\")\n\treturn nil\n}",
"// Logout can be used to log the authenticated user out of the system.\n//\n// The JWT token that was previously in use is added to the JWT Invalidated list\n// thus denying the further use of that token.\nfunc (ctx *PfCtxS) Logout() {\n\tif ctx.token != \"\" {\n\t\tJwt_invalidate(ctx.token, &ctx.token_claims)\n\t}",
"\t/* Invalidate user + token */\n\tctx.user = nil\n\tctx.token = \"\"\n\tctx.token_claims = SessionClaims{}\n}",
"// IsLoggedIn can be used to check if the context has a properly logged in user.\nfunc (ctx *PfCtxS) IsLoggedIn() bool {\n\tif ctx.user == nil {\n\t\treturn false\n\t}",
"\treturn true\n}",
"// IsGroupMember can be used to check if the selected user\n// is a member of the selected group and whether the user\n// can see the group.\nfunc (ctx *PfCtxS) IsGroupMember() bool {\n\tif !ctx.HasSelectedUser() {\n\t\treturn false\n\t}",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\tismember, _, state, err := ctx.sel_group.IsMember(ctx.user.GetUserName())\n\tif err != nil {\n\t\tctx.Log(\"IsGroupMember: \" + err.Error())\n\t\treturn false\n\t}",
"\tif !ismember {\n\t\treturn false\n\t}",
"\t/* Group Admins can always select users, even when blocked */\n\tif ctx.IAmGroupAdmin() {\n\t\treturn true\n\t}",
"\t/* Normal group users, it depends on whether they can see them */\n\treturn state.can_see\n}",
"// IAmGroupAdmin can be used to ask if the logged in user\n// is a groupadmin of the selected group.\nfunc (ctx *PfCtxS) IAmGroupAdmin() bool {\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\tif ctx.IsSysAdmin() {\n\t\treturn true\n\t}",
"\t_, isadmin, _, err := ctx.sel_group.IsMember(ctx.user.GetUserName())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn isadmin\n}",
"// IAmGroupMember can be used to check if the logged in user is a groupmember\nfunc (ctx *PfCtxS) IAmGroupMember() bool {\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\tismember, _, _, err := ctx.sel_group.IsMember(ctx.user.GetUserName())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn ismember\n}",
"// GroupHasWiki can be used to check if the selected group has a wiki module enabled\nfunc (ctx *PfCtxS) GroupHasWiki() bool {\n\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\treturn ctx.sel_group.HasWiki()\n}",
"// GroupHasFile can be used to check if the selected group has a file module enabled\nfunc (ctx *PfCtxS) GroupHasFile() bool {\n\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\treturn ctx.sel_group.HasFile()\n}",
"// GroupHasCalendar can be used to check if the selected group has a calendar module enabled\nfunc (ctx *PfCtxS) GroupHasCalendar() bool {\n\tif !ctx.HasSelectedGroup() {\n\t\treturn false\n\t}",
"\treturn ctx.sel_group.HasCalendar()\n}",
"// SwapSysAdmin swaps a user's privilege between normal user and sysadmin.\nfunc (ctx *PfCtxS) SwapSysAdmin() bool {\n\t/* Not logged, can't be SysAdmin */\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\t/* If they cannot be one, then do not toggle either */\n\tif !ctx.TheUser().CanBeSysAdmin() {\n\t\treturn false\n\t}",
"\t/* Toggle state: SysAdmin <> Regular */\n\tctx.is_sysadmin = !ctx.is_sysadmin",
"\t/* Force generation of a new token */\n\tctx.token = \"\"",
"\treturn true\n}",
"// IsSysAdmin indicates if the current user is a sysadmin\n// and has swapped to it, see SwapSysAdmin.\n//\n// The SAR (System Administation Restrictions) are checked.\n// When the SAR is enabled/configured, one can only become/be\n// a sysadmin when coming from the correct IP address as\n// configured in th SAR list.\nfunc (ctx *PfCtxS) IsSysAdmin() bool {\n\tif !ctx.IsLoggedIn() {\n\t\treturn false\n\t}",
"\t/* Not a SysAdmin, easy */\n\tif !ctx.is_sysadmin {\n\t\treturn false\n\t}",
"\tsys := System_Get()",
"\t/*\n\t * SysAdmin IP Restriction in effect?\n\t *\n\t * Loopback (127.0.0.1 / ::1) are excluded from this restriction\n\t */\n\tif sys.sar_cache == nil || ctx.client_ip.IsLoopback() {\n\t\treturn true\n\t}",
"\t/* Check all the prefixes */\n\tfor _, n := range sys.sar_cache {\n\t\tif n.Contains(ctx.client_ip) {\n\t\t\t/* It is valid */\n\t\t\treturn true\n\t\t}\n\t}",
"\t/* Not in the SARestrict list */\n\treturn false\n}",
"// FromString can be used to parse a string into a Perm object.\n//\n// str can be in the formats:\n// perm1\n// perm1,perm2\n// perm1,perm2,perm3\n//\n// When an unknown permission is encountered, this function will return an error.",
"func FromString(str string) (perm Perm,err error) {",
"\tstr = strings.ToLower(str)",
"\tperm = PERM_NOTHING",
"\tp := strings.Split(str, \",\")\n\tfor _, pm := range p {\n\t\tif pm == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\tfound := false\n\t\tvar i uint\n\t\ti = 0\n\t\tfor _, n := range permnames {\n\t\t\tif pm == n {\n\t\t\t\tperm += 1 << i\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}",
"\t\tif !found {\n\t\t\terr = errors.New(\"Unknown permission: '\" + pm + \"'\")\n\t\t\treturn\n\t\t}\n\t\tbreak\n\t}",
"\terr = nil\n\treturn\n}",
"// String returns the string representation of a Perm.\n//\n// This can be used for in for instance debug output.\nfunc (perm Perm) String() (str string) {",
"\tfor i := 0; i < len(permnames); i++ {\n\t\tp := uint64(math.Pow(float64(2), float64(i)))",
"\t\tif uint64(perm)&p == 0 {\n\t\t\tcontinue\n\t\t}",
"\t\tif str != \"\" {\n\t\t\tstr += \",\"\n\t\t}",
"\t\tstr += permnames[i]\n\t}",
"\treturn str\n}",
"/* IsPerm returns whether the provided Perm is the same Perm as given */\nfunc (perm Perm) IsPerm(perms Perm) bool {\n\treturn perms == perm\n}",
"/* IsSet checks if the perm is in the given set of Perms */\nfunc (perm Perm) IsSet(perms Perm) bool {\n\treturn perms&perm > 0\n}",
"// CheckPerms can verify if the given permissions string is valied for the provided Perms.\n//\n// One of multiple permissions can be specified by OR-ing the permissions together\n// thus test from least to most to see if any of them allows access.\n//\n// To debug permissions, toggle the code-level switch in PDbg and PDbgf().\n//\n// Application permissions are tested at the end when all pitchfork permissions\n// still allow it to proceed.\n//\n// The what parameter indicates the piece of code wanting to see the permissions\n// verified, this thus primarily serves as a debug help.\nfunc (ctx *PfCtxS) CheckPerms(what string, perms Perm) (ok bool, err error) {\n\t/* No error yet */\n\tsys := System_Get()",
"\tctx.PDbgf(what, perms, \"Text: %s\", perms.String())",
"\tif ctx.IsLoggedIn() {\n\t\tctx.PDbgf(what, perms, \"user = %s\", ctx.user.GetUserName())\n\t} else {\n\t\tctx.PDbgf(what, perms, \"user = ::NONE::\")\n\t}",
"\tif ctx.HasSelectedUser() {\n\t\tctx.PDbgf(what, perms, \"sel_user = %s\", ctx.sel_user.GetUserName())\n\t} else {\n\t\tctx.PDbgf(what, perms, \"sel_user = ::NONE::\")\n\t}",
"\tif ctx.HasSelectedGroup() {\n\t\tctx.PDbgf(what, perms, \"sel_group = %s\", ctx.sel_group.GetGroupName())\n\t} else {\n\t\tctx.PDbgf(what, perms, \"sel_group = ::NONE::\")\n\t}",
"\t/* Nobody? */\n\tif perms.IsSet(PERM_NOBODY) {\n\t\tctx.PDbgf(what, perms, \"Nobody\")\n\t\treturn false, errors.New(\"Nobody is allowed\")\n\t}",
"\t/* No permissions? */\n\tif perms.IsPerm(PERM_NOTHING) {\n\t\tctx.PDbgf(what, perms, \"Nothing\")\n\t\treturn true, nil\n\t}",
"\t/* CLI when enabled and user is authenticated */\n\tif perms.IsSet(PERM_CLI) {\n\t\tctx.PDbgf(what, perms, \"CLI\")\n\t\tif ctx.IsLoggedIn() && sys.CLIEnabled {\n\t\t\tctx.PDbgf(what, perms, \"CLI - Enabled\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"CLI is not enabled\")\n\t\t}\n\t}",
"\t/* Loopback calls can always access the API (for tcli) */\n\tif perms.IsSet(PERM_API) {\n\t\tctx.PDbgf(what, perms, \"API\")\n\t\tif sys.APIEnabled {\n\t\t\tctx.PDbgf(what, perms, \"API - Enabled\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"API is not enabled\")\n\t\t}\n\t}",
"\t/* Is OAuth enabled? */\n\tif perms.IsSet(PERM_OAUTH) {\n\t\tctx.PDbgf(what, perms, \"OAuth\")\n\t\tif sys.OAuthEnabled {\n\t\t\tctx.PDbgf(what, perms, \"OAuth - Enabled\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"OAuth is not enabled\")\n\t\t}\n\t}",
"\t/* Loopback? */\n\tif perms.IsSet(PERM_LOOPBACK) {\n\t\tctx.PDbgf(what, perms, \"Loopback\")\n\t\tif ctx.client_ip.IsLoopback() {\n\t\t\tctx.PDbgf(what, perms, \"Is Loopback\")\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\terr = errors.New(\"Not a Loopback\")\n\t\t}\n\t}",
"\t/* User must not be authenticated */\n\tif perms.IsSet(PERM_GUEST) {\n\t\tctx.PDbgf(what, perms, \"Guest\")\n\t\tif !ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"Guest - Not Logged In\")\n\t\t\treturn true, nil\n\t\t}",
"\t\tctx.PDbgf(what, perms, \"Guest - Logged In\")\n\t\treturn false, errors.New(\"Must not be authenticated\")\n\t}",
"\t/* User has to have selected themselves */\n\tif perms.IsSet(PERM_USER_SELF) {\n\t\tctx.PDbgf(what, perms, \"User Self\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User Self - Logged In\")\n\t\t\tif ctx.HasSelectedUser() {\n\t\t\t\tctx.PDbgf(what, perms, \"User Self - Has selected user\")\n\t\t\t\tif ctx.sel_user.GetUserName() == ctx.user.GetUserName() {\n\t\t\t\t\t/* Passed the test */\n\t\t\t\t\tctx.PDbgf(what, perms, \"User Self - It is me\")\n\t\t\t\t\treturn true, nil\n\t\t\t\t} else {\n\t\t\t\t\tctx.PDbgf(what, perms, \"User Self - Other user\")\n\t\t\t\t\terr = errors.New(\"Different user selected\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"No user selected\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* User has to have selected themselves */\n\tif perms.IsSet(PERM_USER_VIEW) {\n\t\tctx.PDbgf(what, perms, \"User View\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User View - Logged In\")\n\t\t\tif ctx.HasSelectedUser() {\n\t\t\t\tctx.PDbgf(what, perms, \"User View - Has selected user\")\n\t\t\t\tif ctx.sel_user.GetUserName() == ctx.user.GetUserName() {\n\t\t\t\t\t/* Passed the test */\n\t\t\t\t\tctx.PDbgf(what, perms, \"User View - It is me\")\n\t\t\t\t\treturn true, nil\n\t\t\t\t} else {\n\t\t\t\t\tok, err = ctx.sel_user.SharedGroups(ctx, ctx.user)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t/* Passed the test */\n\t\t\t\t\t\tctx.PDbgf(what, perms, \"User View - It is in my group\")\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t} else {\n\t\t\t\t\t\tctx.PDbgf(what, perms, \"User View - Other user\")\n\t\t\t\t\t\terr = errors.New(\"Different user selected\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"No user selected\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* User has to be a group member + Wiki enabled */\n\tif perms.IsSet(PERM_GROUP_WIKI) {\n\t\tctx.PDbgf(what, perms, \"Group Wiki?\")\n\t\tif ctx.GroupHasWiki() {\n\t\t\tctx.PDbgf(what, perms, \"HasWiki - ok\")\n\t\t\tif ctx.IsGroupMember() {\n\t\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\terr = errors.New(\"Not a group member\")\n\t\t} else {\n\t\t\terr = errors.New(\"Group does not have a Wiki\")\n\t\t\treturn false, err\n\t\t}\n\t}",
"\t/* User has to be a group member + File enabled */\n\tif perms.IsSet(PERM_GROUP_FILE) {\n\t\tctx.PDbgf(what, perms, \"Group File?\")\n\t\tif ctx.GroupHasFile() {\n\t\t\tctx.PDbgf(what, perms, \"HasFile - ok\")\n\t\t\tif ctx.IsGroupMember() {\n\t\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\terr = errors.New(\"Not a group member\")\n\t\t} else {\n\t\t\terr = errors.New(\"Group does not have a File\")\n\t\t\treturn false, err\n\t\t}\n\t}",
"\t/* User has to be a group member + Calendar enabled */\n\tif perms.IsSet(PERM_GROUP_CALENDAR) {\n\t\tctx.PDbgf(what, perms, \"Group Calendar?\")\n\t\tif ctx.GroupHasCalendar() {\n\t\t\tctx.PDbgf(what, perms, \"HasCalendar - ok\")\n\t\t\tif ctx.IsGroupMember() {\n\t\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\terr = errors.New(\"Not a group member\")\n\t\t} else {\n\t\t\terr = errors.New(\"Group does not have a Calendar\")\n\t\t\treturn false, err\n\t\t}\n\t}",
"\t/* No permissions needed */\n\tif perms.IsSet(PERM_NONE) {\n\t\tctx.PDbgf(what, perms, \"None\")\n\t\t/* Always succeeds */\n\t\treturn true, nil\n\t}",
"\t/* Everything else requires a login */\n\tif !ctx.IsLoggedIn() {\n\t\tctx.PDbgf(what, perms, \"Not Authenticated\")\n\t\terr = errors.New(\"Not authenticated\")\n\t\treturn false, err\n\t}",
"\t/*\n\t * SysAdmin can get away with almost anything\n\t *\n\t * The perms only has the PERM_SYS_ADMIN bit set for clarity\n\t * that that one only has access for sysadmins\n\t */\n\tif ctx.IsSysAdmin() {\n\t\tctx.PDbgf(what, perms, \"SysAdmin?\")\n\t\treturn true, nil\n\t}\n\terr = errors.New(\"Not a SysAdmin\")",
"\t/* User has to be authenticated */\n\tif perms.IsSet(PERM_USER) {\n\t\tctx.PDbgf(what, perms, \"User?\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User - Logged In\")\n\t\t\treturn true, nil\n\t\t}",
"\t\terr = errors.New(\"Not Authenticated\")\n\t}",
"\t/* User has to be a group admin */\n\tif perms.IsSet(PERM_GROUP_ADMIN) {\n\t\tctx.PDbgf(what, perms, \"Group admin?\")\n\t\tif ctx.IAmGroupAdmin() {\n\t\t\tctx.PDbgf(what, perms, \"Group admin - ok\")\n\t\t\treturn true, nil\n\t\t}",
"\t\terr = errors.New(\"Not a group admin\")\n\t}",
"\t/* User has to be a group member */\n\tif perms.IsSet(PERM_GROUP_MEMBER) {\n\t\tctx.PDbgf(what, perms, \"Group member?\")\n\t\tif ctx.IsGroupMember() {\n\t\t\tctx.PDbgf(what, perms, \"Group member - ok\")\n\t\t\treturn true, nil\n\t\t}",
"\t\terr = errors.New(\"Not a group member\")\n\t}",
"\t/* User wants to nominate somebody (even themselves) */\n\tif perms.IsSet(PERM_USER_NOMINATE) {\n\t\tctx.PDbgf(what, perms, \"User Nominate\")\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"User Nominate - Logged In\")\n\t\t\tif ctx.HasSelectedUser() {\n\t\t\t\tctx.PDbgf(what, perms, \"User Nominate - User Selected\")\n\t\t\t\t/* Passed the test */\n\t\t\t\treturn true, nil\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"No user selected\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* Can the user become a SysAdmin? */\n\tif perms.IsSet(PERM_SYS_ADMIN_CAN) {\n\t\tif ctx.IsLoggedIn() {\n\t\t\tctx.PDbgf(what, perms, \"Sys Admin Can - Logged In\")\n\t\t\tif ctx.TheUser().CanBeSysAdmin() {\n\t\t\t\tctx.PDbgf(what, perms, \"Sys Admin Can\")\n\t\t\t\t/* Passed the test */\n\t\t\t\treturn true, nil\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"Can't become SysAdmin\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"Not Authenticated\")\n\t\t}\n\t}",
"\t/* Let the App Check permissions */\n\tif ctx.f_appperms != nil {\n\t\tfinal, _ok, _err := ctx.f_appperms(ctx, what, perms)\n\t\tif final {\n\t\t\treturn _ok, _err\n\t\t}",
"\t\t/* Otherwise we ignore the result as it is not a final decision */\n\t}",
"\tif err == nil {\n\t\t/* Should not happen */\n\t\tpanic(\"Invalid permission bits\")\n\t}",
"\t/* Default Deny + report error */\n\treturn false, err\n}",
"// CheckPermsT can be used to check a Textual version of permissions.\n//\n// Used when the caller has the textual representation of the permissions.\nfunc (ctx *PfCtxS) CheckPermsT(what string, permstr string) (ok bool, err error) {\n\tvar perms Perm\n",
"\tperms,err = FromString(permstr)",
"\tif err != nil {\n\t\treturn\n\t}",
"\treturn ctx.CheckPerms(what, perms)\n}",
"// TheUser returns the currently selected user\nfunc (ctx *PfCtxS) TheUser() (user PfUser) {\n\t/* Return a copy, not a reference */\n\treturn ctx.user\n}",
"// SelectedSelf checks if the logged in user and the selected user are the same.\nfunc (ctx *PfCtxS) SelectedSelf() bool {\n\treturn ctx.IsLoggedIn() &&\n\t\tctx.HasSelectedUser() &&\n\t\tctx.user.GetUserName() == ctx.sel_user.GetUserName()\n}",
"// SelectedUser returns the selected user.\nfunc (ctx *PfCtxS) SelectedUser() (user PfUser) {\n\t/* Return a copy, not a reference */\n\treturn ctx.sel_user\n}",
"// SelectedGroup returns the selected group.\nfunc (ctx *PfCtxS) SelectedGroup() (grp PfGroup) {\n\t/* Return a copy, not a reference */\n\treturn ctx.sel_group\n}",
"// SelectedML returns the selected mailinglist.\nfunc (ctx *PfCtxS) SelectedML() (ml PfML) {\n\t/* Return a copy, not a reference */\n\treturn *ctx.sel_ml\n}",
"// SelectedEmail returns the selected email address.\nfunc (ctx *PfCtxS) SelectedEmail() (email PfUserEmail) {\n\t/* Return a copy, not a reference */\n\treturn *ctx.sel_email\n}",
"// HasSelectedUser returns whether a user was selected.\nfunc (ctx *PfCtxS) HasSelectedUser() bool {\n\treturn ctx.sel_user != nil\n}",
"// HasSelectedGroup returns whether a group was selected.\nfunc (ctx *PfCtxS) HasSelectedGroup() bool {\n\treturn ctx.sel_group != nil\n}",
"// HasSelectedML returns whether a mailinglist was selected.\nfunc (ctx *PfCtxS) HasSelectedML() bool {\n\treturn ctx.sel_ml != nil\n}",
"// SelectMe caused the user to select themselves.\nfunc (ctx *PfCtxS) SelectMe() {\n\tctx.sel_user = ctx.user\n}",
"// SelectUser selects the user if the given permissions are matched.\nfunc (ctx *PfCtxS) SelectUser(username string, perms Perm) (err error) {\n\tctx.PDbgf(\"PfCtxS::SelectUser\", perms, \"%q\", username)",
"\t/* Nothing to select, always works */\n\tif username == \"\" {\n\t\tctx.sel_user = nil\n\t\treturn nil\n\t}",
"\t/* Selecting own user? */\n\ttheuser := ctx.TheUser()\n\tif theuser != nil && theuser.GetUserName() == username {\n\t\t/* Re-use and pass no username to indicate no refresh */\n\t\tctx.sel_user = theuser\n\t\tusername = \"\"\n\t} else {\n\t\tctx.sel_user = ctx.NewUser()\n\t}",
"\terr = ctx.sel_user.Select(ctx, username, perms)\n\tif err != nil {\n\t\tctx.sel_user = nil\n\t}",
"\treturn\n}",
"// SelectGroup selects the group, depending on the permission bits provided.\n//\n// After succesfully selecting, SelectedGroup can be used to retrieve the group.\nfunc (ctx *PfCtxS) SelectGroup(gr_name string, perms Perm) (err error) {\n\tctx.PDbgf(\"SelectGroup\", perms, \"%q\", gr_name)",
"\t/* Nothing to select */\n\tif gr_name == \"\" {\n\t\tctx.sel_group = nil\n\t\treturn nil\n\t}",
"\tctx.sel_group = ctx.NewGroup()\n\terr = ctx.sel_group.Select(ctx, gr_name, perms)\n\tif err != nil {\n\t\tctx.sel_group = nil\n\t}",
"\treturn\n}",
"// SelectML selects a mailinglist depending on the permissions of the logged in user\nfunc (ctx *PfCtxS) SelectML(ml_name string, perms Perm) (err error) {\n\tctx.PDbgf(\"SelectUserML\", perms, \"%q\", ml_name)",
"\tif !ctx.HasSelectedGroup() {\n\t\treturn errors.New(\"No group selected\")\n\t}",
"\t/* Nothing to select */\n\tif ml_name == \"\" {\n\t\tctx.sel_ml = nil\n\t\treturn nil\n\t}",
"\tctx.sel_ml = NewPfML()\n\terr = ctx.sel_ml.Select(ctx, ctx.sel_group, ml_name, perms)",
"\tif err != nil {\n\t\tctx.sel_ml = nil\n\t}",
"\treturn\n}",
"// SelectEmail selects an email address.\n//\n// Users can only select their own email addresses (PERM_USER_SELF).\nfunc (ctx *PfCtxS) SelectEmail(email string) (err error) {\n\tperms := PERM_USER_SELF",
"\tctx.PDbgf(\"SelectEmail\", perms, \"%q\", email)",
"\t/* Nothing to select */\n\tif email == \"\" {\n\t\tctx.sel_email = nil\n\t\treturn nil\n\t}",
"\t/* Fetch email details */\n\tctx.sel_email = NewPfUserEmail()\n\terr = ctx.sel_email.Fetch(email)\n\tif err != nil {\n\t\t/* Did not work */\n\t\tctx.sel_email = nil\n\t\treturn\n\t}",
"\t/* Check Permissions */\n\tvar ok bool\n\tok, _ = ctx.CheckPerms(\"SelectEmail\", perms)\n\tif !ok {\n\t\t/* Nope, no access */\n\t\tctx.sel_email = nil\n\t}",
"\treturn\n}",
"// Err allows printing error messages (syslog/stdout) with details from the context.\nfunc (ctx *PfCtxS) Err(message string) {\n\tErrA(1, message)\n}",
"// Errf allows printing formatted error messages (syslog/stdout) with details from the context.\nfunc (ctx *PfCtxS) Errf(format string, a ...interface{}) {\n\tErrA(1, format, a...)\n}",
"// Log allows printing log messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Log(message string) {\n\tLogA(1, message)\n}",
"// Logf allows printing formatted log messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Logf(format string, a ...interface{}) {\n\tLogA(1, format, a...)\n}",
"// Dbg allows printing debug messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Dbg(message string) {\n\tDbgA(1, message)\n}",
"// Dbgf allows printing formatted debug messages (syslog/stdout) with details from the context\nfunc (ctx *PfCtxS) Dbgf(format string, a ...interface{}) {\n\tDbgA(1, format, a...)\n}",
"// PDbgf is used for permission debugging.\n//\n// It needs to be enabled with a Code level Debug option.\n// Change the 'false' to 'true' and every permission decision will be listed.\n// Remember: sysadmin overrules most permissions, thus test with normal user.\nfunc (ctx *PfCtxS) PDbgf(what string, perm Perm, format string, a ...interface{}) {\n\tif false {\n\t\tctx.Dbgf(\"Perms(\\\"\"+what+\"\\\"/\"+strconv.Itoa(int(perm))+\"): \"+format, a...)\n\t}\n}",
"// Out can be used to print a line to the output for the context (CLI or HTTP).\n//\n// When buffering is disabled, the txt is directly forwarded to a special\n// direct output function.\n//\n// When buffering is enabled, the txt is accumulatd in the output buffer.\nfunc (ctx *PfCtxS) Out(txt string) {\n\tif !ctx.mode_buffered {\n\t\t/* Call the function that takes care of Direct output */\n\t\t_, err := ObjFunc(ctx.outunbuf_obj, ctx.outunbuf_fun, txt)\n\t\tif err != nil {\n\t\t\tctx.Errf(\"Unbuffered output failed: %s\", err.Error())\n\t\t}\n\t} else {\n\t\t/* Buffered output */\n\t\tctx.output += txt\n\t}\n}",
"// Outf can be used to let the Out string be formatted first.\nfunc (ctx *PfCtxS) Outf(format string, a ...interface{}) {\n\tctx.Out(fmt.Sprintf(format, a...))\n}",
"// OutLn ensure that the Out outputted message ends in a newline\nfunc (ctx *PfCtxS) OutLn(format string, a ...interface{}) {\n\tctx.Outf(format+\"\\n\", a...)\n}",
"// SetOutUnbuffered causes the Out* functions to become unbuffered.\n//\n// The object and function passed in are then later used for calling\n// and acually performing the output of the txt with the Out() function.\nfunc (ctx *PfCtxS) SetOutUnbuffered(obj interface{}, fun string) {\n\tobjtrail := []interface{}{obj}\n\tok, obji := ObjHasFunc(objtrail, fun)\n\tif !ok {\n\t\tpanic(\"Unbuffered function \" + fun + \" is missing\")\n\t}",
"\tctx.outunbuf_obj = obji\n\tctx.outunbuf_fun = fun\n}",
"// OutBuffered causes the Out* functions to become buffered.\nfunc (ctx *PfCtxS) OutBuffered(on bool) {\n\tif !on && ctx.outunbuf_fun == \"\" {\n\t\tpanic(\"Can't enable buffered mode without unbuffered function\")\n\t}",
"\tctx.mode_buffered = on\n}",
"// IsBuffered can be used to check if output is being buffered or directly outputted.\nfunc (ctx *PfCtxS) IsBuffered() bool {\n\treturn ctx.mode_buffered\n}",
"// Buffered can be used to return the buffered string.\nfunc (ctx *PfCtxS) Buffered() (o string) {\n\to = ctx.output\n\tctx.output = \"\"\n\treturn\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1336, 1537], "buggy_code_start_loc": [947, 1355], "filenames": ["lib/ctx.go", "lib/struct.go"], "fixing_code_end_loc": [1336, 1538], "fixing_code_start_loc": [947, 1356], "message": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:secluded:trident:1.4.6:rc1:*:*:*:*:*:*", "matchCriteriaId": "52F21E24-C1E2-4E41-B00C-FB5441CCD7CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2."}, {"lang": "es", "value": "Pitchfork, en su versi\u00f3n 1.4.6 RC1, contiene una vulnerabilidad de gesti\u00f3n incorrecta de privilegios en los componentes Trident Pitchfork que puede resultar en que un usuario est\u00e1ndar sin privilegios obtenga permisos de administrador en el portal web. El usuario debe ser capaz de iniciar sesi\u00f3n y podr\u00eda editar su perfil y establecer el permiso \"System Administrator\" en \"yes\" para s\u00ed mismo. La vulnerabilidad parece haber sido solucionada en la versi\u00f3n 1.4.6 RC2."}], "evaluatorComment": null, "id": "CVE-2018-1000133", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-03-16T14:29:44.847", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/9fd07cbe4f93e1367e142016e9a205366680dd54"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/issues/168"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/tridentli/trident/releases/tag/DEV_1.4.6-RC2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://thomas-ward.net/security-advisories/trident-trusted-communications-platform-privilege-escalation-issue-advisory/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-269"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, "type": "CWE-269"}
| 312
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"// Pitchfork struct provides access functions to various ways to inspect or modify contents of structs.\npackage pitchfork",
"import (\n\t\"database/sql\"\n\t\"errors\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)",
"// PTypeField wraps the relect StructField for ease of use in various Struct related functions.\ntype PTypeField struct {\n\treflect.StructField\n}",
"// PTypeWrap simply wraps the relect.StructField into our own PTypField.\nfunc PTypeWrap(f reflect.StructField) PTypeField {\n\treturn PTypeField{f}\n}",
"// PType is used to define the CRUD option.\ntype PType int",
"/* CRUD */\nconst (\n\tPTYPE_CREATE PType = iota /* Create */\n\tPTYPE_READ /* Read */\n\tPTYPE_UPDATE /* Update */\n\tPTYPE_DELETE /* Delete */\n)",
"// PfType is used to get the datatype from either the pftype tag\n// or by basing it on the actual type of the field using reflection.\n//\n// PfType determines if a datatype needs to be recursed and if it\n// is a compound structure.\n//\n// If 'doignore' is set, for some types the return type is 'ignore' to\n// indicate that the field does not need to be processd.\n// This option is for instance used for set/get purposes where\n// 'note' and 'widenote' cannot be changed and thus can be ignored\n// for that purpose.\n//\n// This is primarily a helper function for other functions that\n// parse structs and thus want to adhere to the types and tags.\nfunc PfType(f reflect.StructField, v reflect.Value, doignore bool) (ttype string, dorecurse bool, compound bool) {\n\t/* Forced type */\n\tttype = f.Tag.Get(\"pftype\")",
"\t/* Detected type */\n\tif ttype == \"\" {\n\t\t/* Always ignore functions */\n\t\tif f.Type.Kind() == reflect.Func {\n\t\t\tttype = \"ignore\"\n\t\t\treturn\n\t\t}",
"\t\t/* When the package path is not empty, we ignore the field as it is not exported */\n\t\tif f.PkgPath != \"\" {\n\t\t\t// Dbg(\"Skipping %s (pkg: %#v) - unexported\", f.Name, f.PkgPath)\n\t\t\tttype = \"ignore\"\n\t\t\treturn\n\t\t}",
"\t\tswitch f.Type.Kind() {\n\t\tcase reflect.String:\n\t\t\tttype = \"string\"\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tttype = \"bool\"\n\t\t\tbreak",
"\t\t/* We consider everything just a number, we call it a 'int' out of convienience */\n\t\tcase reflect.Int, reflect.Int64, reflect.Float64, reflect.Uint, reflect.Uint64:\n\t\t\tttype = \"int\"\n\t\t\tbreak",
"\t\tcase reflect.Struct:\n\t\t\tty := StructNameT(f.Type)",
"\t\t\tswitch ty {\n\t\t\tcase \"time.Time\":\n\t\t\t\tttype = \"time\"\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullString\":\n\t\t\t\tttype = \"string\"\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullInt64\", \"database/sql.NullFloat64\":\n\t\t\t\tttype = \"int\"\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullBool\":\n\t\t\t\tttype = \"bool\"\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\t/* Generic struct */\n\t\t\t\tttype = \"struct\"",
"\t\t\t\to := StructRecurse(v)",
"\t\t\t\ttfunc := \"TreatAsString\"\n\t\t\t\tobjtrail := []interface{}{o}\n\t\t\t\tok, _ := ObjHasFunc(objtrail, tfunc)\n\t\t\t\tif ok {\n\t\t\t\t\t/* Really, it is a string, believe me */\n\t\t\t\t\tttype = \"string\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}",
"\t\t\tbreak",
"\t\tcase reflect.Interface:\n\t\t\tttype = \"interface\"\n\t\t\tbreak",
"\t\tcase reflect.Slice:\n\t\t\tttype = \"slice\"\n\t\t\tbreak",
"\t\tcase reflect.Map:\n\t\t\tttype = \"map\"\n\t\t\tbreak",
"\t\tcase reflect.Ptr:\n\t\t\tttype = \"ptr\"\n\t\t\tbreak",
"\t\tcase reflect.Func:\n\t\t\tttype = \"ignore\"\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tpanic(\"Unsupported Reflection Type \" + f.Type.Kind().String() + \": \" + StructNameT(f.Type))\n\t\t}\n\t}",
"\tif doignore {\n\t\t/* Ignore submit buttons and notes */\n\t\tif ttype == \"submit\" || ttype == \"note\" || ttype == \"widenote\" {\n\t\t\tttype = \"ignore\"\n\t\t}\n\t}",
"\t/* Recurse if it is a interface or a generic struct */\n\tif ttype == \"interface\" || ttype == \"struct\" {\n\t\tcompound = true",
"\t\tif ttype != \"struct\" || v.NumField() > 0 {\n\t\t\tdorecurse = true\n\t\t}\n\t}",
"\treturn\n}",
"// StructRecurse is used to recurse through a structure\n// this in the case it is wrapped or embedded.\n//\n// Check CanAddr() so that we do a recurse while\n// we can with ability to set, but recurse otherwise\n// in readonly version.\n//\n// This function is primarily used by other struct related functions\n// and should rarely be called otherwise.\nfunc StructRecurse(v reflect.Value) interface{} {\n\tif v.Kind() != reflect.Interface && v.CanAddr() {\n\t\treturn v.Addr().Interface()\n\t}",
"\treturn v.Interface()\n}",
"// StructNameT returns the name of a structure from a type (T).\n//\n// This function is primarily used by other struct related functions.\nfunc StructNameT(t reflect.Type) string {\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}",
"\tn := t.PkgPath() + \".\" + t.Name()\n\tif n == \".\" {\n\t\tDbgf(\"StructNameT() = %s\", n)\n\t\tpanic(\"StructNameT() could not find a name\")\n\t}\n\treturn n\n}",
"// StructNameObj returns the name of the object (Obj).\n//\n// This function is primarily used by other struct related functions.\nfunc StructNameObj(obj interface{}) string {\n\ts, _ := StructReflect(obj)\n\tn := s.PkgPath() + \".\" + s.Name()\n\tif n == \".\" {\n\t\tDbgf(\"StructNameObj(%s) obj = %#v\", n, obj)\n\t\tpanic(\"StructNameObj() could not find a name\")\n\t}\n\treturn n\n}",
"// StructNameObjTrail returns the full trail of objects as a name.\n//\n// This function is primarily used by other struct related functions.\nfunc StructNameObjTrail(objtrail []interface{}) (oname string) {\n\tfor _, obj := range objtrail {\n\t\tif oname != \"\" {\n\t\t\toname = oname + \"->\"\n\t\t}\n\t\toname = StructNameObj(obj) + oname\n\t}",
"\treturn\n}",
"// StructReflect performs reflection, getting out the type\n// and the value, dereferencing the pointer where needed.\n//\n// This function is primarily used by other struct related functions.\nfunc StructReflect(obj interface{}) (s reflect.Type, va reflect.Value) {\n\ts = reflect.TypeOf(obj)",
"\tif s.Kind() == reflect.Ptr {\n\t\t// Dereference the pointer\n\t\ts = reflect.ValueOf(obj).Type().Elem()\n\t}",
"\t/* Values (Indirect() takes care of pointer to structs) */\n\tva = reflect.Indirect(reflect.ValueOf(obj))",
"\treturn s, va\n}",
"// StructFetchFields builds a SELECT SQL query to retrieve\n// all the fields in a structure from a database\n//\n// The object passed is in parsed, each structure field in-order.\n// The table is used in the FROM query.\n// The q parameter is where the composed SQL query is returned.\n// The ifs parameter is where space for the storage of the to-be-retrieved\n// data is stored.\n//\n// A caller thus calls this with a pointer to an empty query string\n// and an empty ifs array and StructFetchFields then builds the query\n// and returns that in the query argument and in the ifs array.\n//\n// The intermediary 'ifs' is thus used for temporary storage in a way\n// that the SQL library wants to receive it.\n// It also allows for multiple objects to be queried and later stored.\n//\n// This function cooperates with the StructFetchStore function which,\n// after executing the query, can then store the result in the actual structure.\n//\n// This function is typically called from StructFetch or StructFetchMulti\n// which calls StructFetchFields and StructFetchStore.\nfunc StructFetchFields(obj interface{}, table string, q *string, ifs *[]interface{}) (err error) {\n\tfun := \"StructFetchFields() \"",
"\ts, va := StructReflect(obj)",
"\tif s.Kind() == reflect.Interface {\n\t\treturn StructFetchFields(StructRecurse(va), table, q, ifs)\n\t}",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\terr = StructFetchFields(StructRecurse(v), table, q, ifs)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Custom table to take it from? */\n\t\ttname := f.Tag.Get(\"pftable\")\n\t\tif tname == \"\" {\n\t\t\ttname = table\n\t\t}",
"\t\tfname = tname + \".\" + fname",
"\t\tif !v.CanSet() {\n\t\t\terr = errors.New(\"Can't set field '\" + fname + \"' (\" + fun + \")\")\n\t\t\treturn\n\t\t}",
"\t\t/* Start or continue the SELECT statement */\n\t\tif *q == \"\" {\n\t\t\t*q = \"SELECT \"\n\t\t} else {\n\t\t\t*q += \", \"\n\t\t}",
"\t\tcoalesce := f.Tag.Get(\"coalesce\")",
"\t\tftype := f.Type.Kind()",
"\t\t/* Handle 'nil's in the database */\n\t\tswitch ftype {\n\t\tcase reflect.String:\n\t\t\t*q += \"COALESCE(\" + fname + \", '\" + coalesce + \"')\"\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64, reflect.Float64:\n\t\t\t*q += \"COALESCE(\" + fname + \", 0)\"\n\t\t\tbreak",
"\t\tdefault:\n\t\t\t/* Don't COALESCE as we do not know the type */\n\t\t\t*q += fname\n\t\t\tbreak\n\t\t}",
"\t\tvar vr interface{}",
"\t\tswitch ftype {\n\t\tcase reflect.String:\n\t\t\tvr = new(string)\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tvr = new(bool)\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64, reflect.Float64:\n\t\t\tvr = new(int64)\n\t\t\tbreak",
"\t\tcase reflect.Struct:\n\t\t\tty := StructNameT(f.Type)",
"\t\t\tswitch ty {\n\t\t\tcase \"time.Time\":\n\t\t\t\tvr = new(time.Time)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullString\":\n\t\t\t\tvr = new(sql.NullString)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullInt64\":\n\t\t\t\tvr = new(sql.NullInt64)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullFloat64\":\n\t\t\t\tvr = new(sql.NullFloat64)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullBool\":\n\t\t\t\tvr = new(sql.NullBool)\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\tif ttype == \"string\" {\n\t\t\t\t\tvr = new(string)\n\t\t\t\t\tbreak\n\t\t\t\t}",
"\t\t\t\treturn errors.New(fun + \"Variable '\" + fname + \"' is an unknown struct: \" + ty)\n\t\t\t}\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tvar k reflect.Kind\n\t\t\tk = f.Type.Kind()\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown type: \" + k.String())\n\t\t}",
"\t\t*ifs = append(*ifs, vr)\n\t}",
"\treturn nil\n}",
"// StructFetchStore stores the result of a StructFetchFields build query into\n// the object that is passed in.\n//\n// The obj argument represents the object we want the results to be stored in.\n// The ifs argument is the result returned from StructFetchFields, and where\n// the SQL QueryRow/QueryRows call has stored it's result.\n//\n// This function is typically called from StructFetch or StructFetchMulti\n// which calls StructFetchFields and StructFetchStore.\nfunc StructFetchStore(obj interface{}, ifs []interface{}, ifs_n *int) (err error) {\n\tfun := \"StructFetch() \"",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\terr = StructFetchStore(StructRecurse(v), ifs, ifs_n)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\tn := *ifs_n",
"\t\tswitch f.Type.Kind() {\n\t\tcase reflect.String:\n\t\t\tv.SetString(*(ifs[n].(*string)))\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tv.SetBool(*(ifs[n].(*bool)))\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64:\n\t\t\tv.SetInt(*(ifs[n].(*int64)))\n\t\t\tbreak",
"\t\tcase reflect.Float64:\n\t\t\tv.SetFloat(*(ifs[n].(*float64)))\n\t\t\tbreak",
"\t\tcase reflect.Struct:\n\t\t\tty := StructNameT(f.Type)",
"\t\t\tswitch ty {\n\t\t\tcase \"time.Time\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*time.Time))))\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullString\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullString))))\n\t\t\t\treturn",
"\t\t\tcase \"database/sql.NullInt64\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullInt64))))\n\t\t\t\treturn",
"\t\t\tcase \"database/sql.NullFloat64\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullFloat64))))\n\t\t\t\treturn",
"\t\t\tcase \"database/sql.NullBool\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullBool))))\n\t\t\t\treturn",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable '\" + fname + \"' is an unknown struct: \" + ty)\n\t\t\t}\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tvar k reflect.Kind\n\t\t\tk = f.Type.Kind()\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown type: \" + k.String())\n\t\t}",
"\t\t/* Next Field */\n\t\tn++\n\t\t*ifs_n = n\n\t}",
"\treturn nil\n}",
"// StructFetchWhere allows filtering the fields returned with StructFetchFields\n//\n// StructFetch/StructFetchMulti use this to append the 'where' clause portion\n// of the SQL query.\n//\n// The starting query (qi), containing the \"SELECT <field>, <field>\" is passed in.\n// StructFetchWhere adds the FROM portion and any SQL table joins, from the join argument,\n// and then, based on the params and the andor setting creates a WHERE query.\n//\n// andor defines if the where query should be composed of AND or OR statements\n// params defines the parameters that should be verified\n// matchopts defines the way the match in the WHERE should work (LIKE, =, etc)\n// matches defines what should be matched against.\n//\n// The order argument then is additionally used for determining the order of the output.\n//\n// To illustrate the arguments:\n//\n// {qi} FROM {table} {join}\n//\n// and then followed per pair of params/matchopts/matches:\n// {andor} {params} {matchopt} {matches}\n// eg: AND param LIKE '%match%'\n//\n// appended by the {order}.\nfunc StructFetchWhere(qi string, table string, join string, andor DB_AndOr, params []string, matchopts []DB_Op, matches []interface{}, order string) (q string, vals []interface{}) {\n\tq = qi",
"\t/* From which table */\n\tq += \" FROM \" + DB.QI(table)",
"\tif join != \"\" {\n\t\tq += \" \" + join\n\t}",
"\twhere := \"\"\n\tvals = nil",
"\tfor n, p := range params {\n\t\tif where == \"\" {\n\t\t\twhere += \" WHERE \"\n\t\t} else {\n\t\t\tswitch andor {\n\t\t\tcase DB_OP_AND:\n\t\t\t\twhere += \" AND \"\n\t\t\t\tbreak",
"\t\t\tcase DB_OP_OR:\n\t\t\t\twhere += \" OR \"\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\tpanic(\"Invalid andor\")\n\t\t\t}\n\t\t}",
"\t\tpp := strings.Split(p, \".\")\n\t\tif len(pp) == 2 {\n\t\t\twhere += DB.QI(pp[0]) + \".\" + DB.QI(pp[1])\n\t\t} else {\n\t\t\twhere += DB.QI(p)\n\t\t}",
"\t\tswitch matchopts[n] {\n\t\tcase DB_OP_LIKE:\n\t\t\twhere += \" LIKE \"\n\t\t\tbreak",
"\t\tcase DB_OP_ILIKE:\n\t\t\twhere += \" ILIKE \"\n\t\t\tbreak",
"\t\tcase DB_OP_EQ:\n\t\t\twhere += \" = \"\n\t\t\tbreak",
"\t\tcase DB_OP_NE:\n\t\t\twhere += \" <> \"\n\t\t\tbreak",
"\t\tcase DB_OP_LE:\n\t\t\twhere += \" <= \"\n\t\t\tbreak",
"\t\tcase DB_OP_GE:\n\t\t\twhere += \" >= \"\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tpanic(\"Unsupported Match option\")\n\t\t}",
"\t\twhere += \"$\" + strconv.Itoa(n+1)\n\t\tvals = append(vals, matches[n])\n\t}",
"\t/* Append the WHERE portion */\n\tq += where",
"\tq += \" \" + strings.TrimSpace(order)",
"\treturn\n}",
"// StructFetchMulti returns multiple objects using StructFetchFields.\n//\n// The newobject function is called to create a new object to be filled in.\n// Any type of object can be returned. These objects are returned in the objs parameter.\n//\n// See StructFetchWhere for the table/jon/andor/params/matchops/matches/order arguments.\n//\n// The limit argument can be used to add a LIMIT to the SQL query.\n// The offset argument can be used to add a OFFSET to the SQL query.\nfunc StructFetchMulti(newobject func() interface{}, table string, join string, andor DB_AndOr, params []string, matchopts []DB_Op, matches []interface{}, order string, offset int, limit int) (objs []interface{}, err error) {\n\tvar ifs []interface{} = nil",
"\tq := \"\"\n\tobjs = nil",
"\tobj := newobject()",
"\terr = StructFetchFields(obj, table, &q, &ifs)\n\tif err != nil {\n\t\treturn\n\t}",
"\tif q == \"\" {\n\t\treturn nil, errors.New(\"No fields to retrieve\")\n\t}",
"\tq, vals := StructFetchWhere(q, table, join, andor, params, matchopts, matches, order)",
"\tif limit != 0 {\n\t\tq += \" LIMIT \"\n\t\tDB.Q_AddArg(&q, &vals, limit)\n\t}",
"\tif offset != 0 {\n\t\tq += \" OFFSET \"\n\t\tDB.Q_AddArg(&q, &vals, offset)\n\t}",
"\t/* Execute the query & scan it */\n\tvar rows *Rows\n\trows, err = DB.Query(q, vals...)\n\tif err != nil {\n\t\treturn\n\t}",
"\tdefer rows.Close()",
"\t/* There should be one */\n\tfor rows.Next() {\n\t\terr = rows.Scan(ifs...)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}",
"\t\to := newobject()\n\t\tn := 0",
"\t\terr = StructFetchStore(o, ifs, &n)\n\t\tobjs = append(objs, o)\n\t}",
"\treturn objs, nil\n}",
"// StructFetchA exposes extra options than the simpler StructFetch\n// it is used to fetch data from a database directly into a structure\n// based on the fields in that structure and the parameters given.\n//\n// See StructFetchWhere for the table/jon/andor/params/matchops/matches/order arguments.\n//\n// The notfoundok boolean is used to return ErrNoRows when set to true.\n// Otherwise it returns a string 'not found' error.\n// This toggle primarily exists to ease the difference between programmatically\n// calling this function, and wanting to process the ErrNoRows further or\n// wanting to return the result to the CLI or other human readable error construct.\nfunc StructFetchA(obj interface{}, table string, join string, params []string, matches []string, order string, notfoundok bool) (err error) {\n\tq := \"\"",
"\tvar ifs []interface{} = nil",
"\terr = StructFetchFields(obj, table, &q, &ifs)\n\tif err != nil {\n\t\treturn\n\t}",
"\tif q == \"\" {\n\t\terr = errors.New(\"No fields to retrieve\")\n\t\treturn\n\t}",
"\tvar matchopts []DB_Op\n\tfor _, _ = range params {\n\t\tmatchopts = append(matchopts, DB_OP_EQ)\n\t}",
"\tvar imatches []interface{}\n\tfor _, m := range matches {\n\t\timatches = append(imatches, m)\n\t}",
"\tq, vals := StructFetchWhere(q, table, join, DB_OP_AND, params, matchopts, imatches, order)",
"\t/* Only want one back */\n\tq += \" LIMIT 1\"",
"\t/* Execute the query & scan it */\n\tvar rows *Rows\n\trows, err = DB.Query(q, vals...)\n\tif err != nil {\n\t\treturn\n\t}",
"\tdefer rows.Close()",
"\t/* There should be one */\n\tif !rows.Next() {\n\t\tif !notfoundok {\n\t\t\terr = errors.New(\"No entry in \" + table + \" with that ID\")\n\t\t\treturn\n\t\t}",
"\t\treturn ErrNoRows\n\t}",
"\terr = rows.Scan(ifs...)\n\tif err != nil {\n\t\treturn\n\t}",
"\tn := 0\n\terr = StructFetchStore(obj, ifs, &n)",
"\treturn\n}",
"// StructFetch calls StructFetchA() but avoids the need to specify a few\n// parameters that are not always needed (join and ordering).\n//\n// See StructFetchA for the details to the arguments.\nfunc StructFetch(obj interface{}, table string, params []string, matches []string) (err error) {\n\treturn StructFetchA(obj, table, \"\", params, matches, \"\", false)\n}",
"// StructOp defines what operation to perform on a structure\ntype StructOp uint",
"const (\n\tSTRUCTOP_SET StructOp = iota /* Set the item */\n\tSTRUCTOP_ADD /* Add the item */\n\tSTRUCTOP_REMOVE /* Remove the item */\n)",
"// StructFieldMod allows changing a field identified by fname to a new value.\n//\n// Set/add/remove are possible depending on datatype: set for non-slice, add/remove are slice only.\n//\n// This function is typically called through StructMod().\nfunc StructFieldMod(op StructOp, fname string, f reflect.StructField, v reflect.Value, value interface{}) (err error) {\n\tfun := \"StructFieldMod() \"",
"\t/* What kind of object is this? */\n\tkind := f.Type.Kind()",
"\t/* Check that this type of operand is actually allowed */\n\tswitch op {\n\tcase STRUCTOP_SET:\n\t\tif kind == reflect.Slice {\n\t\t\treturn errors.New(\"Can't 'set' a slice type: \" + StructNameT(f.Type))\n\t\t}\n\t\tbreak",
"\tcase STRUCTOP_ADD:\n\t\tif kind != reflect.Slice {\n\t\t\treturn errors.New(\"Can't add to non-slice type: \" + StructNameT(f.Type))\n\t\t}\n\t\tbreak",
"\tcase STRUCTOP_REMOVE:\n\t\tif kind != reflect.Slice {\n\t\t\treturn errors.New(\"Can't remove from non-slice type: \" + StructNameT(f.Type))\n\t\t}\n\t\tbreak",
"\tdefault:\n\t\treturn errors.New(\"Unknown STRUCTOP\")\n\t}",
"\tvo := reflect.ValueOf(value)",
"\tswitch kind {\n\tcase reflect.String:\n\t\tv.SetString(value.(string))\n\t\treturn nil",
"\tcase reflect.Bool:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tv.SetBool(IsTrue(value.(string)))\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tv.SetBool(value.(bool))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown source type: \" + vo.Kind().String())\n\t\t}\n\t\treturn nil",
"\tcase reflect.Int, reflect.Int64:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tnumber, err := strconv.ParseInt(value.(string), 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t}\n\t\t\tv.SetInt(number)\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64:\n\t\t\tv.SetInt(value.(int64))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t}\n\t\treturn nil",
"\tcase reflect.Uint, reflect.Uint64:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tnumber, err := strconv.Atoi(value.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t}\n\t\t\tv.SetUint(uint64(number))\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64:\n\t\t\tv.SetUint(value.(uint64))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t}\n\t\treturn nil",
"\tcase reflect.Float64:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tnumber, err := strconv.ParseFloat(value.(string), 64)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid floating number encountered: '\" + value.(string) + \"'\")\n\t\t\t}\n\t\t\tv.SetFloat(number)\n\t\t\tbreak",
"\t\tcase reflect.Float64:\n\t\t\tv.SetFloat(value.(float64))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t}\n\t\treturn nil",
"\tcase reflect.Struct:\n\t\tty := StructNameT(f.Type)\n\t\tswitch ty {\n\t\tcase \"time.Time\":\n\t\t\tvar no time.Time\n\t\t\tno, err = time.Parse(Config.TimeFormat, value.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\treturn",
"\t\tcase \"database/sql.NullString\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tno := sql.NullString{String: value.(string), Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}\n\t\t\treturn",
"\t\tcase \"database/sql.NullInt64\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tvalid := true\n\t\t\t\tvar number int64 = 0\n\t\t\t\tif value.(string) == \"\" {\n\t\t\t\t\tvalid = false\n\t\t\t\t} else {\n\t\t\t\t\tnumber, err = strconv.ParseInt(value.(string), 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t\t}\n\t\t\t\t}",
"\t\t\t\tno := sql.NullInt64{Int64: number, Valid: valid}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tcase reflect.Int, reflect.Int64:\n\t\t\t\tno := ToNullInt64(value.(int64))\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}\n\t\t\treturn",
"\t\tcase \"database/sql.NullFloat64\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tvalid := true\n\t\t\t\tvar number float64\n\t\t\t\tif value.(string) == \"\" {\n\t\t\t\t\tvalid = false\n\t\t\t\t} else {\n\t\t\t\t\tnumber, err = strconv.ParseFloat(value.(string), 64)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid floating number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t}\n\t\t\t\tno := sql.NullFloat64{Float64: number, Valid: valid}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tcase reflect.Float64:\n\t\t\t\tno := sql.NullFloat64{Float64: value.(float64), Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}\n\t\t\treturn",
"\t\tcase \"database/sql.NullBool\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tyesno := IsTrue(value.(string))\n\t\t\t\tno := sql.NullBool{Bool: yesno, Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tcase reflect.Bool:\n\t\t\t\tno := sql.NullBool{Bool: value.(bool), Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}",
"\t\t\treturn\n\t\t}",
"\t\t/* Check if the object supports the Scan interface */\n\t\to := StructRecurse(v)\n\t\ttfunc := \"Scan\"\n\t\tobjtrail := []interface{}{o}\n\t\tok, obj := ObjHasFunc(objtrail, tfunc)\n\t\tif ok {\n\t\t\t/* Scan() the value in */\n\t\t\tres, err2 := ObjFunc(obj, tfunc, value)\n\t\t\tif err2 == nil {\n\t\t\t\terr2, ok := res[0].Interface().(error)\n\t\t\t\tif ok {\n\t\t\t\t\terr = err2\n\t\t\t\t}",
"\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\treturn errors.New(fun + \"Variable '\" + fname + \"' is an unknown struct: \" + ty)",
"\tcase reflect.Slice:\n\t\tswitch op {\n\t\tcase STRUCTOP_ADD:\n\t\t\t/* What do we store here? */\n\t\t\tvn := v.Type().String()",
"\t\t\tswitch vn {\n\t\t\tcase \"[]string\":\n\t\t\t\tbreak",
"\t\t\tcase \"[]int\":\n\t\t\t\t/* Input a string or a int? */\n\t\t\t\tswitch vo.Kind() {\n\t\t\t\tcase reflect.String:\n\t\t\t\t\tnumber, err := strconv.Atoi(value.(string))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t\t}\n\t\t\t\t\tvo = reflect.ValueOf(number)\n\t\t\t\t\tbreak",
"\t\t\t\tcase reflect.Uint, reflect.Uint64:\n\t\t\t\t\tvo = reflect.ValueOf(value.(uint64))\n\t\t\t\t\tbreak",
"\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(fun + \" detected a unsupported type for \" + fname)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}",
"\t\t\tn := reflect.Append(v, vo)\n\t\t\tv.Set(n)\n\t\t\treturn nil",
"\t\tcase STRUCTOP_REMOVE:\n\t\t\t/* What do we store here? */\n\t\t\tvn := v.Type().String()",
"\t\t\t/* Found it? */\n\t\t\tfound := -1",
"\t\t\t/* First, find the item we want to remove */\n\t\t\tfor k := 0; found == -1 && k < v.Len(); k += 1 {\n\t\t\t\tswitch vn {\n\t\t\t\tcase \"[]string\":\n\t\t\t\t\tov := v.Index(k).Interface().(string)\n\t\t\t\t\tif ov == value.(string) {\n\t\t\t\t\t\tfound = k\n\t\t\t\t\t}\n\t\t\t\t\tbreak",
"\t\t\t\tcase \"[]int\", \"[]uint64\":\n\t\t\t\t\tvar ov uint64",
"\t\t\t\t\tswitch vn {\n\t\t\t\t\tcase \"[]int\":\n\t\t\t\t\t\tov = uint64(v.Index(k).Interface().(int))\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tcase \"[]uint64\":\n\t\t\t\t\t\tov = v.Index(k).Interface().(uint64)\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn errors.New(\"Unsupported integer?\")\n\t\t\t\t\t}",
"\t\t\t\t\t/* Input a string or a int? */\n\t\t\t\t\tswitch vo.Kind() {\n\t\t\t\t\tcase reflect.String:\n\t\t\t\t\t\tnumber, err := strconv.Atoi(value.(string))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tif uint64(number) == ov {\n\t\t\t\t\t\t\tfound = k\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tcase reflect.Uint:\n\t\t\t\t\t\tnumber := value.(int)",
"\t\t\t\t\t\tif uint64(number) == ov {\n\t\t\t\t\t\t\tfound = k\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tbreak",
"\t\t\t\t\tcase reflect.Uint64:\n\t\t\t\t\t\tnumber := value.(uint64)\n\t\t\t\t\t\tif number == ov {\n\t\t\t\t\t\t\tfound = k\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn errors.New(fun + \" detected a unsupported type for \" + fname)\n\t\t\t\t\t}\n\t\t\t\t\tbreak",
"\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(\"Do not support removing from slice of type \" + vn)\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif found == -1 {\n\t\t\t\treturn errors.New(\"Item not found, thus cannot remove\")\n\t\t\t}",
"\t\t\t/* Create a new slice with all elements except the found one */\n\t\t\tn := v.Slice(0, found)\n\t\t\tn = reflect.AppendSlice(n, v.Slice(found+1, v.Len()))",
"\t\t\t/* Set the slice to the new one, which does not have the item */\n\t\t\tv.Set(n)\n\t\t\treturn nil\n\t\t}",
"\t\t/* Handled nicer above */\n\t\tpanic(\"Cannot apply STRUCTOP_SET to a Slice\")",
"\t/* TODO support reflect.Map */",
"\tdefault:\n\t\tvar k reflect.Kind\n\t\tk = f.Type.Kind()\n\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown type: \" + k.String())\n\t}\n}",
"// structModA modifies a single field.\n//\n// This is called by StructMod, recursively to be able to support nested structs.\nfunc StructModA(op StructOp, obj interface{}, field string, value interface{}) (done bool, err error) {\n\tfun := \"StructMod() \"",
"\tdone = false",
"\tfield = strings.ToLower(field)",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tdone, err = StructModA(op, StructRecurse(v), field, value)\n\t\t\tif done || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Not this field? */\n\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\tif !v.CanSet() {\n\t\t\terr = errors.New(fun + \"Can't set field '\" + fname + \"'\")\n\t\t\treturn\n\t\t}",
"\t\tdone = true\n\t\terr = StructFieldMod(op, fname, f, v, value)\n\t\treturn\n\t}",
"\treturn\n}",
"// StructMod modifies a single field of a object.\n//\n// Given the object obj, it finds the 'field' in the structure and sets it to the given value.\n//\n// ErrNoRows is returned when no such field was found.\n// Other errors, eg permission errors or inability to set a field can also be returned.\n// An error of nil is returned if the change of the value succeeded.\nfunc StructMod(op StructOp, obj interface{}, field string, value interface{}) (err error) {\n\tdone, err := StructModA(op, obj, field, value)\n\tif err == nil && !done {\n\t\terr = ErrNoRows\n\t\treturn\n\t}",
"\treturn\n}",
"// structVarsA is the recursive portion of StructVars and thus only called by that function\nfunc StructVars(ctx PfCtx, obj interface{}, ptype PType, doignore bool) (vars map[string]string, err error) {\n\tobjtrail := []interface{}{}\n\tvars = make(map[string]string)\n\terr = StructVarsA(ctx, objtrail, obj, ptype, doignore, vars)\n\treturn vars, err\n}",
"// StructVars returns all fields in a struct that can be retrieved or modified, returning a map of strings.\n//\n// StructVars takes an object to inspect and a ptype indicating what permissions the field should satisfy for them to be included.\n//\n// The map consists out of the key being the fieldname and the value being the ToString()'d value of the field.\n//\n// Permissions are tested against the provided ptype and the context.\nfunc StructVarsA(ctx PfCtx, objtrail []interface{}, obj interface{}, ptype PType, doignore bool, vars map[string]string) (err error) {\n\ts, va := StructReflect(obj)",
"\tobjtrail = append([]interface{}{obj}, objtrail...)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\t// ctx.Dbgf(\"StructVars: %s [%s]\", f.Name, f.Type.Kind().String())",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\terr = StructVarsA(ctx, objtrail, StructRecurse(v), ptype, doignore, vars)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\tvar ok bool",
"\t\tok, _, err = StructPermCheck(ctx, ptype, objtrail, PTypeWrap(f))\n\t\t// ctx.Dbgf(\"StructVars: %s - permcheck: %s, err: %v\", f.Name, YesNo(ok), err)\n\t\tif err != nil {\n\t\t\tskipfailperm := f.Tag.Get(\"pfskipfailperm\")\n\t\t\tif skipfailperm == \"\" {\n\t\t\t\tctx.Dbgf(\"StructVars: %s - permcheck: %s, err: %s\", f.Name, YesNo(ok), err.Error())\n\t\t\t}\n\t\t\tcontinue\n\t\t}",
"\t\tif !ok && ttype != \"ptr\" && ttype != \"struct\" {\n\t\t\t// oname := StructNameObjTrail(objtrail)\n\t\t\t// ctx.Dbg(\"NOT SHOWING: field = %s, ttype = %s\", oname+\":\"+fname, ttype)\n\t\t\tcontinue\n\t\t}",
"\t\tvars[fname] = ttype\n\t}",
"\terr = nil\n\treturn\n}",
"// StructDetails_Options defines options to apply when checking StructDetails\ntype StructDetails_Options int",
"const (\n\tSD_None = 0 /* No Options */\n\tSD_Perms_Check StructDetails_Options = 0 << iota /* Check Permissions */\n\tSD_Perms_Ignore /* Ignore Permissions */\n\tSD_Tags_Require /* Require Tags */\n\tSD_Tags_Ignore /* Ignore Tags */\n)",
"// structDetailsA is the recursive portion of StructDetails, see that function for more details\nfunc StructDetailsA(ctx PfCtx, obj interface{}, field string, opts StructDetails_Options) (ftype string, fname string, fvalue string, err error) {\n\tcheckperms := false\n\tif opts&SD_Perms_Check > 0 {\n\t\tcheckperms = true\n\t}",
"\trequiretags := false\n\tif opts&SD_Tags_Require > 0 {\n\t\trequiretags = true\n\t}",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname = f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Ignore the field completely? */\n\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tif fname == field {\n\t\t\t\treturn \"ignore\", \"\", \"\", errors.New(\"Field is ignored\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tftype, fname, fvalue, err = StructDetailsA(ctx, StructRecurse(v), field, opts)\n\t\t\tif ftype != \"\" || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif requiretags && f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Wrong field, skip it */\n\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\tif checkperms {\n\t\t\tok := true\n\t\t\tpermstr := f.Tag.Get(\"pfset\")",
"",
"\t\t\tok, err = ctx.CheckPermsT(\"StructDetails(\"+fname+\")\", permstr)\n\t\t\tif !ok {\n\t\t\t\treturn \"\", \"\", \"\", err\n\t\t\t}\n\t\t}",
"\t\treturn \"string\", fname, ToString(v.Interface()), nil\n\t}",
"\treturn \"\", \"\", \"\", nil\n}",
"// StructDetails returns the details of a structure's field.\n//\n// It determines the type of the field and the string value of the field.\n//\n// The opts can be used to influence if permission checking needs to be done\n// and if tags are required to be present for the field to be checked.\nfunc StructDetails(ctx PfCtx, obj interface{}, field string, opts StructDetails_Options) (ftype string, fname string, fvalue string, err error) {\n\tfield = strings.ToLower(field)",
"\tftype, fname, fvalue, err = StructDetailsA(ctx, obj, field, opts)\n\tif err == nil && ftype == \"\" {\n\t\treturn \"unknown\", \"\", \"\", errors.New(\"Unknown Field: \" + field + \" (StructDetails)\")\n\t}",
"\treturn\n}",
"// structTagA is the recursive portion of StructTag, see that function for details\nfunc StructTagA(obj interface{}, field string, tag string) (val string, err error) {\n\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tval, err = StructTagA(StructRecurse(v), field, tag)\n\t\t\tif err != nil || val != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\tval = f.Tag.Get(tag)\n\t\treturn\n\t}",
"\treturn \"\", nil\n}",
"// StructTag retrieves the requested tag from a field in a structure.\n//\n// Any type of object can be provided, it will be recursed incase of embedded structs.\n//\n// The field indicates the name of the structure's field.\n// The tag indicates which tag to get for that field.\n//\n// The value returned is the content of the tag for the requested field.\nfunc StructTag(obj interface{}, field string, tag string) (val string, err error) {\n\tfield = strings.ToLower(field)",
"\tval, err = StructTagA(obj, field, tag)\n\tif err == nil && val == \"\" {\n\t\treturn \"\", errors.New(\"Unknown Field: \" + field + \" (StructTag)\")\n\t}",
"\treturn\n}",
"// structMenuA is the recursive portion of StructMenu\n//\n// See StructMenu for more details.\nfunc StructMenuA(ctx PfCtx, subjects []string, objtrail []interface{}, obj interface{}, onlyslices bool, fun PfFunc, isedit bool, nargs int) (menu PfMenu, err error) {\n\t/* Prepend this object to the trail */\n\tobjtrail = append([]interface{}{obj}, objtrail...)",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tm, err := StructMenuA(ctx, subjects, objtrail, StructRecurse(v), onlyslices, fun, isedit, nargs)\n\t\t\tif err != nil {\n\t\t\t\treturn PfMenu{}, err\n\t\t\t}",
"\t\t\tmenu.Add(m.M...)\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Ignore slices when we don't want them, others if we only want slices */\n\t\tif (ttype == \"slice\" && onlyslices == false) || (ttype != \"slice\" && onlyslices == true) {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Options from the Tag of the structure */\n\t\tlabel := f.Tag.Get(\"label\")\n\t\tif label != \"\" {\n\t\t\t/* Only translate when the label is specifically set */\n\t\t\tlabel = TranslateObj(ctx, objtrail, label)\n\t\t} else {\n\t\t\tlabel = f.Name\n\t\t}",
"\t\thint := f.Tag.Get(\"hint\")\n\t\tif hint != \"\" {\n\t\t\t/* Only translate when the hint is specifically set */\n\t\t\thint = TranslateObj(ctx, objtrail, hint)\n\t\t}",
"\t\t/* Default description to the label */\n\t\tdesc := label",
"\t\t/* Append the hint to the description */\n\t\tif hint != \"\" {\n\t\t\tdesc += \" - \" + hint\n\t\t}",
"\t\t/* Ignore the field completely? */\n\t\tignore := f.Tag.Get(\"pfignore\")\n\t\tif ignore == \"yes\" {\n\t\t\tcontinue\n\t\t}",
"\t\tvar perms Perm\n\t\tvar tag string",
"\t\tif isedit {\n\t\t\ttag = \"pfset\"\n\t\t} else {\n\t\t\ttag = \"pfget\"\n\t\t}",
"\t\tset := f.Tag.Get(tag)",
"\t\terr = perms.FromString(set)",
"\t\tif err != nil {\n\t\t\treturn\n\t\t}",
"\t\tif perms == PERM_NOTHING {\n\t\t\t/* Default permissions is to allow getting/setting of anything */\n\t\t\tperms = PERM_NONE\n\t\t}",
"\t\tvar ok bool\n\t\tok, _ = ctx.CheckPerms(\"StructMenu(\"+fname+\")\", perms)\n\t\tif !ok {\n\t\t\t/* Also change to 'ok, err' above */\n\t\t\t/* Dbgf(\"StructMenu(%s) Skipping (tag: %s), err: %s\", fname, tag, err.Error()) */\n\t\t\tcontinue\n\t\t}",
"\t\t/* Initial subjects */\n\t\tsubj := subjects",
"\t\tif isedit {\n\t\t\totype := \"\"",
"\t\t\tswitch ttype {\n\t\t\tcase \"bool\":\n\t\t\t\totype = \"#bool\"\n\t\t\t\tbreak",
"\t\t\tcase \"int\":\n\t\t\t\totype = \"#int\"\n\t\t\t\tbreak",
"\t\t\tcase \"file\":\n\t\t\t\totype = \"#file\"\n\t\t\t\totype += \"#\" + f.Tag.Get(\"pfmaximagesize\")",
"\t\t\t\tb64 := f.Tag.Get(\"pfb64\")\n\t\t\t\totype += \"#\" + NormalizeBoolean(b64)\n\t\t\t\tbreak",
"\t\t\tcase \"string\", \"text\", \"tel\":\n\t\t\t\totype = \"#string\"\n\t\t\t\tbreak",
"\t\t\tcase \"time\":\n\t\t\t\totype = \"#time\"\n\t\t\t\tbreak",
"\t\t\tcase \"struct\":\n\t\t\t\tbreak",
"\t\t\tcase \"slice\":\n\t\t\t\tbreak",
"\t\t\tcase \"map\":\n\t\t\t\tbreak",
"\t\t\tcase \"ptr\":\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\tpanic(\"Unknown Type for field \" + fname + \", type \" + ttype)\n\t\t\t}",
"\t\t\tsubj = append(subj, fname+otype)\n\t\t}",
"\t\tvar m PfMEntry\n\t\tm.Cmd = fname\n\t\tm.Fun = fun\n\t\tm.Args_min = nargs\n\t\tm.Args_max = nargs\n\t\tm.Args = subj\n\t\tm.Perms = perms\n\t\tm.Desc = desc",
"\t\tmenu.Add(m)\n\t}",
"\treturn menu, nil\n}",
"// StructMenu can create \"get\", \"set\", \"add\" and \"remove\" CLI menus\n// from a given structure.\n//\n// The subjects parameter indicates the field(s) that indicates what\n// should be provided as an argument to select that specific object.\n//\n// The object is an example object (just the structure, no values needed)\n// that has a set of fields with tags. The tags are used to retrieve the\n// labels and descriptions for the field, but also the permissions needed\n// to configure that field.\n//\n// onlyslices is used to switch between a 'get'/'set' menu and a 'add'/'remove' menu.\n// When onlyslices is true only fields that are slices are listed, these will\n// require an 'add'/'remove' construct instead of being able to be directly 'set' or 'get'.\n//\n// When a function is provided, the menu becomes a 'set' or add/remove menu (for slices).\n// When no function is provided the resulting menu is a 'get' menu.\n// The permissions for set/get are adhered to.\n//\n// See the example for a minimal example. The User portion of Pitchfork makes a good\n// full example on how this code is used, see lib/user.go user_get/user_set etc.\nfunc StructMenu(ctx PfCtx, subjects []string, obj interface{}, onlyslices bool, fun PfFunc) (menu PfMenu, err error) {\n\tvar isedit bool",
"\t/* Select the Object */\n\tctx.SelectObject(&obj)",
"\t/* Number of subjects */\n\tnargs := len(subjects)",
"\t/* Edit or not? */\n\tif fun != nil {\n\t\tisedit = true",
"\t\t/* Edit's require one more argument */\n\t\tnargs++\n\t} else {\n\t\tfun = structGet\n\t}",
"\t/* Recursive call */\n\tobjtrail := []interface{}{}\n\treturn StructMenuA(ctx, subjects, objtrail, obj, onlyslices, fun, isedit, nargs)\n}",
"// structGetA is the recursive part of StructGet.\nfunc structGetA(ctx PfCtx, obj interface{}, field string) (done bool, err error) {\n\ts, va := StructReflect(obj)",
"\tdone = false",
"\tif s.Kind() == reflect.Interface {\n\t\treturn structGetA(ctx, StructRecurse(va), field)\n\t}",
"\tif s.Kind() != reflect.Struct {\n\t\terr = errors.New(\"Error: parameter is not a struct/interface but \" + s.String() + \" (structGet)\")\n\t\treturn\n\t}",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tdone, err = structGetA(ctx, StructRecurse(v), field)\n\t\t\tif done || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Wrong field -> next! */\n\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Ignore the field completely? */\n\t\tignore := f.Tag.Get(\"pfignore\")\n\t\tif ignore == \"yes\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/*\n\t\t * Note: structGet does not check permissions,\n\t\t * it is only used by StructMenu() which does\n\t\t * check for permissions\n\t\t */\n\t\tstr := ToString(v.Interface())\n\t\tctx.OutLn(str)",
"\t\tdone = true\n\t\terr = nil\n\t\treturn\n\t}",
"\treturn\n}",
"// Create a \"get\" menu from a struct -- helper function of StructMenu.\nfunc structGet(ctx PfCtx, args []string) (err error) {\n\tobj := ctx.SelectedObject()",
"\tif obj == nil {\n\t\treturn errors.New(\"No object selected\")\n\t}",
"\tfield := ctx.GetLastPart()",
"\tdone, err := structGetA(ctx, obj, field)\n\tif err == nil && !done {\n\t\terr = errors.New(\"Unknown property\")\n\t}",
"\treturn\n}",
"// ToString converts any type of object to a string representation.\nfunc ToString(v interface{}) (str string) {\n\ts, _ := StructReflect(v)",
"\tswitch s.Kind() {",
"\tcase reflect.String:\n\t\treturn v.(string)",
"\tcase reflect.Bool:\n\t\treturn YesNo(v.(bool))",
"\tcase reflect.Int:\n\t\treturn strconv.Itoa(v.(int))",
"\tcase reflect.Uint:\n\t\treturn strconv.FormatUint(uint64(v.(uint)), 10)",
"\tcase reflect.Int64:\n\t\treturn strconv.FormatInt(v.(int64), 10)",
"\tcase reflect.Uint64:\n\t\treturn strconv.FormatUint(v.(uint64), 10)",
"\tcase reflect.Float64:\n\t\treturn strconv.FormatFloat(v.(float64), 'E', -1, 64)",
"\tcase reflect.Struct:\n\t\tty := StructNameT(s)",
"\t\tswitch ty {\n\t\tcase \"time.Time\":\n\t\t\tno := v.(time.Time)\n\t\t\treturn no.Format(Config.TimeFormat)",
"\t\tcase \"database/sql.NullString\":\n\t\t\tno := v.(sql.NullString)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.String)",
"\t\tcase \"database/sql.NullInt64\":\n\t\t\tno := v.(sql.NullInt64)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.Int64)",
"\t\tcase \"database/sql.NullFloat64\":\n\t\t\tno := v.(sql.NullFloat64)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.Float64)",
"\t\tcase \"database/sql.NullBool\":\n\t\t\tno := v.(sql.NullBool)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.Bool)",
"\t\tdefault:\n\t\t\t/* Try if the object has a String() function */\n\t\t\ttfunc := \"String\"\n\t\t\tobjtrail := []interface{}{v}\n\t\t\tok, obj := ObjHasFunc(objtrail, tfunc)\n\t\t\tif ok {\n\t\t\t\ts, err := ObjFuncStr(obj, tfunc)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn s\n\t\t\t\t}\n\t\t\t}",
"\t\t\tpanic(\"ToString() Unhandled Struct Type '\" + ty + \"' : \" + s.String())\n\t\t}\n\t}",
"\tpanic(\"ToString() Unhandled Type: \" + s.String())\n}",
"// ObjFuncI retains a object.\ntype ObjFuncI struct {\n\tobj interface{}\n}",
"// ObjHasFunc is used to determine of an object has the given function,\n// returning the (embedded) object that has the function\n//\n// An objecttrail consisting of one or more objects is passed in, thus\n// allowing a function to be found in a nested set of objects.\n//\n// This call should be used before ObjFunc to ensure the function\n// has the given object, and to select the correct object.\nfunc ObjHasFunc(objtrail []interface{}, fun string) (ok bool, obj ObjFuncI) {\n\tok = false",
"\tfor _, ob := range objtrail {\n\t\to := reflect.ValueOf(ob)",
"\t\tif o.IsValid() {\n\t\t\tf := o.MethodByName(fun)\n\t\t\tif f.IsValid() {\n\t\t\t\tok = true\n\t\t\t\tobj.obj = ob\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tErrf(\"Not a valid object: %#v\", obj)\n\t\t}\n\t}",
"\treturn\n}",
"// ObjFunc calls, when available, a function in an object and returns it's result\n//\n// The 'fun' is retrieved from the given object, as typically found with ObjHasFunc.\n// The function is then verified to be able to accept the parameters specified by params.\n// And the function is then called dynamically.\n//\n// One major use-case is the Translate function of objects, where we typically do\n// not know what object we will be calling that function on.\nfunc ObjFunc(obj ObjFuncI, fun string, params ...interface{}) (result []reflect.Value, err error) {\n\tresult = nil\n\terr = nil",
"\to := reflect.ValueOf(obj.obj)\n\tif !o.IsValid() {\n\t\terr = errors.New(\"Not a valid object\")\n\t\treturn\n\t}",
"\tf := o.MethodByName(fun)\n\tif !f.IsValid() {\n\t\terr = errors.New(\"Unknown Function \" + fun)\n\t\treturn\n\t}",
"\tpnum := f.Type().NumIn()\n\tif (f.Type().IsVariadic() && len(params) < pnum) || (!f.Type().IsVariadic() && len(params) != pnum) {\n\t\tvtxt := \"\"\n\t\tif f.Type().IsVariadic() {\n\t\t\tvtxt = \" [note: variadic]\"\n\t\t}\n\t\terr = errors.New(\"Wrong amount of parameters, got: \" + strconv.Itoa(len(params)) + \", need: \" + strconv.Itoa(pnum) + vtxt)\n\t\tpanic(\"Need more\")\n\t}",
"\tin := make([]reflect.Value, len(params))",
"\tfor k, param := range params {\n\t\t/* Avoid a null Value */\n\t\tif param == nil {\n\t\t\tin[k] = reflect.ValueOf(¶m).Elem()\n\t\t} else {\n\t\t\tin[k] = reflect.ValueOf(param)\n\t\t}\n\t}",
"\tresult = f.Call(in)\n\treturn\n}",
"// ObjFuncIface calls a function of an object and returns the result of an interface.\n//\n// See ObjFunc for more details on the parameters.\nfunc ObjFuncIface(obj ObjFuncI, fun string, params ...interface{}) (iface interface{}, err error) {\n\tres, err := ObjFunc(obj, fun, params...)",
"\tif err == nil {\n\t\tiface = res[0].Interface()\n\t} else {\n\t\tiface = nil\n\t}",
"\treturn\n}",
"// ObjFuncStr calls a function of an object and returns a string.\n//\n// When the returned type of the called function is not a string,\n// this code will return a string indicating that in the string.\n// Similary the string will be filled with a notion that the call failed.\n// Next to having a non-nil error return.\n//\n// See ObjFunc for more details on the parameters.\nfunc ObjFuncStr(obj ObjFuncI, fun string, params ...interface{}) (str string, err error) {\n\tres, err := ObjFunc(obj, fun, params...)",
"\tif err == nil {\n\t\tif res[0].Kind() == reflect.String {\n\t\t\tstr = res[0].String()\n\t\t} else {\n\t\t\tstr = fun + \"()-not-a-string\"\n\t\t}\n\t} else {\n\t\tstr = fun + \"()-failed\"\n\t}",
"\treturn\n}",
"// objPermCheck calls custom PermCheck function on an object and determines\n// if one has access and is allowed to edit or not.\n//\n// The ptype is used for the permission check to determine if read or write access is needed.\n// Per-application permissions could be more strict and be full CRUD-style.\n//\n// The return of 'ok' indicates that it is allowed to access the field.\n// The allowedit indicates if the field is allowed to be edited/modified.\n// The error indicates whether anything failed, nil indicates success.\n//\n// This function is used by StructPermCheck.\nfunc ObjPermCheck(ctx PfCtx, obj ObjFuncI, ptype PType, f PTypeField) (ok bool, allowedit bool, err error) {\n\tres, err := ObjFunc(obj, \"PermCheck\", ctx, ptype, f)",
"\tif err == nil {\n\t\tvar varok bool",
"\t\tok = res[0].Interface().(bool)\n\t\tallowedit = res[1].Interface().(bool)\n\t\terr, varok = res[2].Interface().(error)\n\t\tif !varok {\n\t\t\terr = nil\n\t\t}\n\t} else {\n\t\tok = false\n\t\tallowedit = false\n\t}",
"\treturn\n}",
"// StructPermCheck checks the permissions of a struct,\n// and determines if one has acccess and is allowed to edit.\n//\n// The ptype allows specifying of CRUD-style (Create/Read/Update/Delete) permissions to check for.\n// The objtrail is passed in, to allow a surrounding object to be used for Permission checking.\n// The PermCheck function of the first object in the trail is used for permission checks next to\n// the pitchfork pfget/pfset permissions.\n//\n// The f parameter is the field we are checking permissions for.\n//\n// The return of 'ok' indicates that it is allowed to access the field.\n// The allowedit indicates if the field is allowed to be edited/modified.\n// The error indicates whether anything failed, nil indicates success.\nfunc StructPermCheck(ctx PfCtx, ptype PType, objtrail []interface{}, f PTypeField) (ok bool, allowedit bool, err error) {\n\tswitch ptype {\n\tcase PTYPE_CREATE, PTYPE_UPDATE:\n\t\tallowedit = true\n\t\tbreak",
"\tcase PTYPE_READ, PTYPE_DELETE:\n\t\tallowedit = false\n\t\tbreak",
"\tdefault:\n\t\tpanic(\"Unknown ptype\")\n\t}",
"\t/* Check Application specific permissions */\n\tapp_perms, obj := ObjHasFunc(objtrail, \"PermCheck\")\n\tif app_perms {\n\t\tok, allowedit, err = ObjPermCheck(ctx, obj, ptype, f)",
"\t\tif err == nil && !ok && allowedit {\n\t\t\t/* Retry in read mode */\n\t\t\tptype = PTYPE_READ\n\t\t\tok, allowedit, err = ObjPermCheck(ctx, obj, ptype, f)\n\t\t}",
"\t\t/* Errors or denies give a direct answer */\n\t\tif err != nil || !ok {\n\t\t\treturn\n\t\t}\n\t}",
"\t/* If there is a Pitchfork tag it also gets to make a decision */\n\ttag := \"pfget\"\n\tif allowedit {\n\t\ttag = \"pfset\"\n\t}",
"\tpermstr := f.Tag.Get(tag)",
"\tif !app_perms || permstr != \"\" {\n\t\tok, err = ctx.CheckPermsT(\"StructPermCheck(\"+f.Name+\"/\"+tag+\"/\"+permstr+\")\", permstr)\n\t\tif !ok && allowedit {\n\t\t\tallowedit = false\n\t\t\ttag = \"pfget\"\n\t\t\tpermstr := f.Tag.Get(tag)",
"\t\t\t/* Use the fail for pfset, if no pfget is defined and pfset errored */\n\t\t\tif permstr == \"\" && err != nil {\n\t\t\t\treturn\n\t\t\t}",
"\t\t\t/* Fall back */\n\t\t\tok, err = ctx.CheckPermsT(\"StructPermCheck(\"+f.Name+\"/get/\"+permstr+\")\", permstr)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}",
"\treturn\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,
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,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1336, 1537], "buggy_code_start_loc": [947, 1355], "filenames": ["lib/ctx.go", "lib/struct.go"], "fixing_code_end_loc": [1336, 1538], "fixing_code_start_loc": [947, 1356], "message": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:secluded:trident:1.4.6:rc1:*:*:*:*:*:*", "matchCriteriaId": "52F21E24-C1E2-4E41-B00C-FB5441CCD7CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2."}, {"lang": "es", "value": "Pitchfork, en su versi\u00f3n 1.4.6 RC1, contiene una vulnerabilidad de gesti\u00f3n incorrecta de privilegios en los componentes Trident Pitchfork que puede resultar en que un usuario est\u00e1ndar sin privilegios obtenga permisos de administrador en el portal web. El usuario debe ser capaz de iniciar sesi\u00f3n y podr\u00eda editar su perfil y establecer el permiso \"System Administrator\" en \"yes\" para s\u00ed mismo. La vulnerabilidad parece haber sido solucionada en la versi\u00f3n 1.4.6 RC2."}], "evaluatorComment": null, "id": "CVE-2018-1000133", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-03-16T14:29:44.847", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/9fd07cbe4f93e1367e142016e9a205366680dd54"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/issues/168"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/tridentli/trident/releases/tag/DEV_1.4.6-RC2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://thomas-ward.net/security-advisories/trident-trusted-communications-platform-privilege-escalation-issue-advisory/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-269"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, "type": "CWE-269"}
| 312
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"// Pitchfork struct provides access functions to various ways to inspect or modify contents of structs.\npackage pitchfork",
"import (\n\t\"database/sql\"\n\t\"errors\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)",
"// PTypeField wraps the relect StructField for ease of use in various Struct related functions.\ntype PTypeField struct {\n\treflect.StructField\n}",
"// PTypeWrap simply wraps the relect.StructField into our own PTypField.\nfunc PTypeWrap(f reflect.StructField) PTypeField {\n\treturn PTypeField{f}\n}",
"// PType is used to define the CRUD option.\ntype PType int",
"/* CRUD */\nconst (\n\tPTYPE_CREATE PType = iota /* Create */\n\tPTYPE_READ /* Read */\n\tPTYPE_UPDATE /* Update */\n\tPTYPE_DELETE /* Delete */\n)",
"// PfType is used to get the datatype from either the pftype tag\n// or by basing it on the actual type of the field using reflection.\n//\n// PfType determines if a datatype needs to be recursed and if it\n// is a compound structure.\n//\n// If 'doignore' is set, for some types the return type is 'ignore' to\n// indicate that the field does not need to be processd.\n// This option is for instance used for set/get purposes where\n// 'note' and 'widenote' cannot be changed and thus can be ignored\n// for that purpose.\n//\n// This is primarily a helper function for other functions that\n// parse structs and thus want to adhere to the types and tags.\nfunc PfType(f reflect.StructField, v reflect.Value, doignore bool) (ttype string, dorecurse bool, compound bool) {\n\t/* Forced type */\n\tttype = f.Tag.Get(\"pftype\")",
"\t/* Detected type */\n\tif ttype == \"\" {\n\t\t/* Always ignore functions */\n\t\tif f.Type.Kind() == reflect.Func {\n\t\t\tttype = \"ignore\"\n\t\t\treturn\n\t\t}",
"\t\t/* When the package path is not empty, we ignore the field as it is not exported */\n\t\tif f.PkgPath != \"\" {\n\t\t\t// Dbg(\"Skipping %s (pkg: %#v) - unexported\", f.Name, f.PkgPath)\n\t\t\tttype = \"ignore\"\n\t\t\treturn\n\t\t}",
"\t\tswitch f.Type.Kind() {\n\t\tcase reflect.String:\n\t\t\tttype = \"string\"\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tttype = \"bool\"\n\t\t\tbreak",
"\t\t/* We consider everything just a number, we call it a 'int' out of convienience */\n\t\tcase reflect.Int, reflect.Int64, reflect.Float64, reflect.Uint, reflect.Uint64:\n\t\t\tttype = \"int\"\n\t\t\tbreak",
"\t\tcase reflect.Struct:\n\t\t\tty := StructNameT(f.Type)",
"\t\t\tswitch ty {\n\t\t\tcase \"time.Time\":\n\t\t\t\tttype = \"time\"\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullString\":\n\t\t\t\tttype = \"string\"\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullInt64\", \"database/sql.NullFloat64\":\n\t\t\t\tttype = \"int\"\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullBool\":\n\t\t\t\tttype = \"bool\"\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\t/* Generic struct */\n\t\t\t\tttype = \"struct\"",
"\t\t\t\to := StructRecurse(v)",
"\t\t\t\ttfunc := \"TreatAsString\"\n\t\t\t\tobjtrail := []interface{}{o}\n\t\t\t\tok, _ := ObjHasFunc(objtrail, tfunc)\n\t\t\t\tif ok {\n\t\t\t\t\t/* Really, it is a string, believe me */\n\t\t\t\t\tttype = \"string\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}",
"\t\t\tbreak",
"\t\tcase reflect.Interface:\n\t\t\tttype = \"interface\"\n\t\t\tbreak",
"\t\tcase reflect.Slice:\n\t\t\tttype = \"slice\"\n\t\t\tbreak",
"\t\tcase reflect.Map:\n\t\t\tttype = \"map\"\n\t\t\tbreak",
"\t\tcase reflect.Ptr:\n\t\t\tttype = \"ptr\"\n\t\t\tbreak",
"\t\tcase reflect.Func:\n\t\t\tttype = \"ignore\"\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tpanic(\"Unsupported Reflection Type \" + f.Type.Kind().String() + \": \" + StructNameT(f.Type))\n\t\t}\n\t}",
"\tif doignore {\n\t\t/* Ignore submit buttons and notes */\n\t\tif ttype == \"submit\" || ttype == \"note\" || ttype == \"widenote\" {\n\t\t\tttype = \"ignore\"\n\t\t}\n\t}",
"\t/* Recurse if it is a interface or a generic struct */\n\tif ttype == \"interface\" || ttype == \"struct\" {\n\t\tcompound = true",
"\t\tif ttype != \"struct\" || v.NumField() > 0 {\n\t\t\tdorecurse = true\n\t\t}\n\t}",
"\treturn\n}",
"// StructRecurse is used to recurse through a structure\n// this in the case it is wrapped or embedded.\n//\n// Check CanAddr() so that we do a recurse while\n// we can with ability to set, but recurse otherwise\n// in readonly version.\n//\n// This function is primarily used by other struct related functions\n// and should rarely be called otherwise.\nfunc StructRecurse(v reflect.Value) interface{} {\n\tif v.Kind() != reflect.Interface && v.CanAddr() {\n\t\treturn v.Addr().Interface()\n\t}",
"\treturn v.Interface()\n}",
"// StructNameT returns the name of a structure from a type (T).\n//\n// This function is primarily used by other struct related functions.\nfunc StructNameT(t reflect.Type) string {\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}",
"\tn := t.PkgPath() + \".\" + t.Name()\n\tif n == \".\" {\n\t\tDbgf(\"StructNameT() = %s\", n)\n\t\tpanic(\"StructNameT() could not find a name\")\n\t}\n\treturn n\n}",
"// StructNameObj returns the name of the object (Obj).\n//\n// This function is primarily used by other struct related functions.\nfunc StructNameObj(obj interface{}) string {\n\ts, _ := StructReflect(obj)\n\tn := s.PkgPath() + \".\" + s.Name()\n\tif n == \".\" {\n\t\tDbgf(\"StructNameObj(%s) obj = %#v\", n, obj)\n\t\tpanic(\"StructNameObj() could not find a name\")\n\t}\n\treturn n\n}",
"// StructNameObjTrail returns the full trail of objects as a name.\n//\n// This function is primarily used by other struct related functions.\nfunc StructNameObjTrail(objtrail []interface{}) (oname string) {\n\tfor _, obj := range objtrail {\n\t\tif oname != \"\" {\n\t\t\toname = oname + \"->\"\n\t\t}\n\t\toname = StructNameObj(obj) + oname\n\t}",
"\treturn\n}",
"// StructReflect performs reflection, getting out the type\n// and the value, dereferencing the pointer where needed.\n//\n// This function is primarily used by other struct related functions.\nfunc StructReflect(obj interface{}) (s reflect.Type, va reflect.Value) {\n\ts = reflect.TypeOf(obj)",
"\tif s.Kind() == reflect.Ptr {\n\t\t// Dereference the pointer\n\t\ts = reflect.ValueOf(obj).Type().Elem()\n\t}",
"\t/* Values (Indirect() takes care of pointer to structs) */\n\tva = reflect.Indirect(reflect.ValueOf(obj))",
"\treturn s, va\n}",
"// StructFetchFields builds a SELECT SQL query to retrieve\n// all the fields in a structure from a database\n//\n// The object passed is in parsed, each structure field in-order.\n// The table is used in the FROM query.\n// The q parameter is where the composed SQL query is returned.\n// The ifs parameter is where space for the storage of the to-be-retrieved\n// data is stored.\n//\n// A caller thus calls this with a pointer to an empty query string\n// and an empty ifs array and StructFetchFields then builds the query\n// and returns that in the query argument and in the ifs array.\n//\n// The intermediary 'ifs' is thus used for temporary storage in a way\n// that the SQL library wants to receive it.\n// It also allows for multiple objects to be queried and later stored.\n//\n// This function cooperates with the StructFetchStore function which,\n// after executing the query, can then store the result in the actual structure.\n//\n// This function is typically called from StructFetch or StructFetchMulti\n// which calls StructFetchFields and StructFetchStore.\nfunc StructFetchFields(obj interface{}, table string, q *string, ifs *[]interface{}) (err error) {\n\tfun := \"StructFetchFields() \"",
"\ts, va := StructReflect(obj)",
"\tif s.Kind() == reflect.Interface {\n\t\treturn StructFetchFields(StructRecurse(va), table, q, ifs)\n\t}",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\terr = StructFetchFields(StructRecurse(v), table, q, ifs)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Custom table to take it from? */\n\t\ttname := f.Tag.Get(\"pftable\")\n\t\tif tname == \"\" {\n\t\t\ttname = table\n\t\t}",
"\t\tfname = tname + \".\" + fname",
"\t\tif !v.CanSet() {\n\t\t\terr = errors.New(\"Can't set field '\" + fname + \"' (\" + fun + \")\")\n\t\t\treturn\n\t\t}",
"\t\t/* Start or continue the SELECT statement */\n\t\tif *q == \"\" {\n\t\t\t*q = \"SELECT \"\n\t\t} else {\n\t\t\t*q += \", \"\n\t\t}",
"\t\tcoalesce := f.Tag.Get(\"coalesce\")",
"\t\tftype := f.Type.Kind()",
"\t\t/* Handle 'nil's in the database */\n\t\tswitch ftype {\n\t\tcase reflect.String:\n\t\t\t*q += \"COALESCE(\" + fname + \", '\" + coalesce + \"')\"\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64, reflect.Float64:\n\t\t\t*q += \"COALESCE(\" + fname + \", 0)\"\n\t\t\tbreak",
"\t\tdefault:\n\t\t\t/* Don't COALESCE as we do not know the type */\n\t\t\t*q += fname\n\t\t\tbreak\n\t\t}",
"\t\tvar vr interface{}",
"\t\tswitch ftype {\n\t\tcase reflect.String:\n\t\t\tvr = new(string)\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tvr = new(bool)\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64, reflect.Float64:\n\t\t\tvr = new(int64)\n\t\t\tbreak",
"\t\tcase reflect.Struct:\n\t\t\tty := StructNameT(f.Type)",
"\t\t\tswitch ty {\n\t\t\tcase \"time.Time\":\n\t\t\t\tvr = new(time.Time)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullString\":\n\t\t\t\tvr = new(sql.NullString)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullInt64\":\n\t\t\t\tvr = new(sql.NullInt64)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullFloat64\":\n\t\t\t\tvr = new(sql.NullFloat64)\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullBool\":\n\t\t\t\tvr = new(sql.NullBool)\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\tif ttype == \"string\" {\n\t\t\t\t\tvr = new(string)\n\t\t\t\t\tbreak\n\t\t\t\t}",
"\t\t\t\treturn errors.New(fun + \"Variable '\" + fname + \"' is an unknown struct: \" + ty)\n\t\t\t}\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tvar k reflect.Kind\n\t\t\tk = f.Type.Kind()\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown type: \" + k.String())\n\t\t}",
"\t\t*ifs = append(*ifs, vr)\n\t}",
"\treturn nil\n}",
"// StructFetchStore stores the result of a StructFetchFields build query into\n// the object that is passed in.\n//\n// The obj argument represents the object we want the results to be stored in.\n// The ifs argument is the result returned from StructFetchFields, and where\n// the SQL QueryRow/QueryRows call has stored it's result.\n//\n// This function is typically called from StructFetch or StructFetchMulti\n// which calls StructFetchFields and StructFetchStore.\nfunc StructFetchStore(obj interface{}, ifs []interface{}, ifs_n *int) (err error) {\n\tfun := \"StructFetch() \"",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\terr = StructFetchStore(StructRecurse(v), ifs, ifs_n)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\tn := *ifs_n",
"\t\tswitch f.Type.Kind() {\n\t\tcase reflect.String:\n\t\t\tv.SetString(*(ifs[n].(*string)))\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tv.SetBool(*(ifs[n].(*bool)))\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64:\n\t\t\tv.SetInt(*(ifs[n].(*int64)))\n\t\t\tbreak",
"\t\tcase reflect.Float64:\n\t\t\tv.SetFloat(*(ifs[n].(*float64)))\n\t\t\tbreak",
"\t\tcase reflect.Struct:\n\t\t\tty := StructNameT(f.Type)",
"\t\t\tswitch ty {\n\t\t\tcase \"time.Time\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*time.Time))))\n\t\t\t\tbreak",
"\t\t\tcase \"database/sql.NullString\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullString))))\n\t\t\t\treturn",
"\t\t\tcase \"database/sql.NullInt64\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullInt64))))\n\t\t\t\treturn",
"\t\t\tcase \"database/sql.NullFloat64\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullFloat64))))\n\t\t\t\treturn",
"\t\t\tcase \"database/sql.NullBool\":\n\t\t\t\tv.Set(reflect.ValueOf(*(ifs[n].(*sql.NullBool))))\n\t\t\t\treturn",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable '\" + fname + \"' is an unknown struct: \" + ty)\n\t\t\t}\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tvar k reflect.Kind\n\t\t\tk = f.Type.Kind()\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown type: \" + k.String())\n\t\t}",
"\t\t/* Next Field */\n\t\tn++\n\t\t*ifs_n = n\n\t}",
"\treturn nil\n}",
"// StructFetchWhere allows filtering the fields returned with StructFetchFields\n//\n// StructFetch/StructFetchMulti use this to append the 'where' clause portion\n// of the SQL query.\n//\n// The starting query (qi), containing the \"SELECT <field>, <field>\" is passed in.\n// StructFetchWhere adds the FROM portion and any SQL table joins, from the join argument,\n// and then, based on the params and the andor setting creates a WHERE query.\n//\n// andor defines if the where query should be composed of AND or OR statements\n// params defines the parameters that should be verified\n// matchopts defines the way the match in the WHERE should work (LIKE, =, etc)\n// matches defines what should be matched against.\n//\n// The order argument then is additionally used for determining the order of the output.\n//\n// To illustrate the arguments:\n//\n// {qi} FROM {table} {join}\n//\n// and then followed per pair of params/matchopts/matches:\n// {andor} {params} {matchopt} {matches}\n// eg: AND param LIKE '%match%'\n//\n// appended by the {order}.\nfunc StructFetchWhere(qi string, table string, join string, andor DB_AndOr, params []string, matchopts []DB_Op, matches []interface{}, order string) (q string, vals []interface{}) {\n\tq = qi",
"\t/* From which table */\n\tq += \" FROM \" + DB.QI(table)",
"\tif join != \"\" {\n\t\tq += \" \" + join\n\t}",
"\twhere := \"\"\n\tvals = nil",
"\tfor n, p := range params {\n\t\tif where == \"\" {\n\t\t\twhere += \" WHERE \"\n\t\t} else {\n\t\t\tswitch andor {\n\t\t\tcase DB_OP_AND:\n\t\t\t\twhere += \" AND \"\n\t\t\t\tbreak",
"\t\t\tcase DB_OP_OR:\n\t\t\t\twhere += \" OR \"\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\tpanic(\"Invalid andor\")\n\t\t\t}\n\t\t}",
"\t\tpp := strings.Split(p, \".\")\n\t\tif len(pp) == 2 {\n\t\t\twhere += DB.QI(pp[0]) + \".\" + DB.QI(pp[1])\n\t\t} else {\n\t\t\twhere += DB.QI(p)\n\t\t}",
"\t\tswitch matchopts[n] {\n\t\tcase DB_OP_LIKE:\n\t\t\twhere += \" LIKE \"\n\t\t\tbreak",
"\t\tcase DB_OP_ILIKE:\n\t\t\twhere += \" ILIKE \"\n\t\t\tbreak",
"\t\tcase DB_OP_EQ:\n\t\t\twhere += \" = \"\n\t\t\tbreak",
"\t\tcase DB_OP_NE:\n\t\t\twhere += \" <> \"\n\t\t\tbreak",
"\t\tcase DB_OP_LE:\n\t\t\twhere += \" <= \"\n\t\t\tbreak",
"\t\tcase DB_OP_GE:\n\t\t\twhere += \" >= \"\n\t\t\tbreak",
"\t\tdefault:\n\t\t\tpanic(\"Unsupported Match option\")\n\t\t}",
"\t\twhere += \"$\" + strconv.Itoa(n+1)\n\t\tvals = append(vals, matches[n])\n\t}",
"\t/* Append the WHERE portion */\n\tq += where",
"\tq += \" \" + strings.TrimSpace(order)",
"\treturn\n}",
"// StructFetchMulti returns multiple objects using StructFetchFields.\n//\n// The newobject function is called to create a new object to be filled in.\n// Any type of object can be returned. These objects are returned in the objs parameter.\n//\n// See StructFetchWhere for the table/jon/andor/params/matchops/matches/order arguments.\n//\n// The limit argument can be used to add a LIMIT to the SQL query.\n// The offset argument can be used to add a OFFSET to the SQL query.\nfunc StructFetchMulti(newobject func() interface{}, table string, join string, andor DB_AndOr, params []string, matchopts []DB_Op, matches []interface{}, order string, offset int, limit int) (objs []interface{}, err error) {\n\tvar ifs []interface{} = nil",
"\tq := \"\"\n\tobjs = nil",
"\tobj := newobject()",
"\terr = StructFetchFields(obj, table, &q, &ifs)\n\tif err != nil {\n\t\treturn\n\t}",
"\tif q == \"\" {\n\t\treturn nil, errors.New(\"No fields to retrieve\")\n\t}",
"\tq, vals := StructFetchWhere(q, table, join, andor, params, matchopts, matches, order)",
"\tif limit != 0 {\n\t\tq += \" LIMIT \"\n\t\tDB.Q_AddArg(&q, &vals, limit)\n\t}",
"\tif offset != 0 {\n\t\tq += \" OFFSET \"\n\t\tDB.Q_AddArg(&q, &vals, offset)\n\t}",
"\t/* Execute the query & scan it */\n\tvar rows *Rows\n\trows, err = DB.Query(q, vals...)\n\tif err != nil {\n\t\treturn\n\t}",
"\tdefer rows.Close()",
"\t/* There should be one */\n\tfor rows.Next() {\n\t\terr = rows.Scan(ifs...)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}",
"\t\to := newobject()\n\t\tn := 0",
"\t\terr = StructFetchStore(o, ifs, &n)\n\t\tobjs = append(objs, o)\n\t}",
"\treturn objs, nil\n}",
"// StructFetchA exposes extra options than the simpler StructFetch\n// it is used to fetch data from a database directly into a structure\n// based on the fields in that structure and the parameters given.\n//\n// See StructFetchWhere for the table/jon/andor/params/matchops/matches/order arguments.\n//\n// The notfoundok boolean is used to return ErrNoRows when set to true.\n// Otherwise it returns a string 'not found' error.\n// This toggle primarily exists to ease the difference between programmatically\n// calling this function, and wanting to process the ErrNoRows further or\n// wanting to return the result to the CLI or other human readable error construct.\nfunc StructFetchA(obj interface{}, table string, join string, params []string, matches []string, order string, notfoundok bool) (err error) {\n\tq := \"\"",
"\tvar ifs []interface{} = nil",
"\terr = StructFetchFields(obj, table, &q, &ifs)\n\tif err != nil {\n\t\treturn\n\t}",
"\tif q == \"\" {\n\t\terr = errors.New(\"No fields to retrieve\")\n\t\treturn\n\t}",
"\tvar matchopts []DB_Op\n\tfor _, _ = range params {\n\t\tmatchopts = append(matchopts, DB_OP_EQ)\n\t}",
"\tvar imatches []interface{}\n\tfor _, m := range matches {\n\t\timatches = append(imatches, m)\n\t}",
"\tq, vals := StructFetchWhere(q, table, join, DB_OP_AND, params, matchopts, imatches, order)",
"\t/* Only want one back */\n\tq += \" LIMIT 1\"",
"\t/* Execute the query & scan it */\n\tvar rows *Rows\n\trows, err = DB.Query(q, vals...)\n\tif err != nil {\n\t\treturn\n\t}",
"\tdefer rows.Close()",
"\t/* There should be one */\n\tif !rows.Next() {\n\t\tif !notfoundok {\n\t\t\terr = errors.New(\"No entry in \" + table + \" with that ID\")\n\t\t\treturn\n\t\t}",
"\t\treturn ErrNoRows\n\t}",
"\terr = rows.Scan(ifs...)\n\tif err != nil {\n\t\treturn\n\t}",
"\tn := 0\n\terr = StructFetchStore(obj, ifs, &n)",
"\treturn\n}",
"// StructFetch calls StructFetchA() but avoids the need to specify a few\n// parameters that are not always needed (join and ordering).\n//\n// See StructFetchA for the details to the arguments.\nfunc StructFetch(obj interface{}, table string, params []string, matches []string) (err error) {\n\treturn StructFetchA(obj, table, \"\", params, matches, \"\", false)\n}",
"// StructOp defines what operation to perform on a structure\ntype StructOp uint",
"const (\n\tSTRUCTOP_SET StructOp = iota /* Set the item */\n\tSTRUCTOP_ADD /* Add the item */\n\tSTRUCTOP_REMOVE /* Remove the item */\n)",
"// StructFieldMod allows changing a field identified by fname to a new value.\n//\n// Set/add/remove are possible depending on datatype: set for non-slice, add/remove are slice only.\n//\n// This function is typically called through StructMod().\nfunc StructFieldMod(op StructOp, fname string, f reflect.StructField, v reflect.Value, value interface{}) (err error) {\n\tfun := \"StructFieldMod() \"",
"\t/* What kind of object is this? */\n\tkind := f.Type.Kind()",
"\t/* Check that this type of operand is actually allowed */\n\tswitch op {\n\tcase STRUCTOP_SET:\n\t\tif kind == reflect.Slice {\n\t\t\treturn errors.New(\"Can't 'set' a slice type: \" + StructNameT(f.Type))\n\t\t}\n\t\tbreak",
"\tcase STRUCTOP_ADD:\n\t\tif kind != reflect.Slice {\n\t\t\treturn errors.New(\"Can't add to non-slice type: \" + StructNameT(f.Type))\n\t\t}\n\t\tbreak",
"\tcase STRUCTOP_REMOVE:\n\t\tif kind != reflect.Slice {\n\t\t\treturn errors.New(\"Can't remove from non-slice type: \" + StructNameT(f.Type))\n\t\t}\n\t\tbreak",
"\tdefault:\n\t\treturn errors.New(\"Unknown STRUCTOP\")\n\t}",
"\tvo := reflect.ValueOf(value)",
"\tswitch kind {\n\tcase reflect.String:\n\t\tv.SetString(value.(string))\n\t\treturn nil",
"\tcase reflect.Bool:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tv.SetBool(IsTrue(value.(string)))\n\t\t\tbreak",
"\t\tcase reflect.Bool:\n\t\t\tv.SetBool(value.(bool))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown source type: \" + vo.Kind().String())\n\t\t}\n\t\treturn nil",
"\tcase reflect.Int, reflect.Int64:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tnumber, err := strconv.ParseInt(value.(string), 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t}\n\t\t\tv.SetInt(number)\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64:\n\t\t\tv.SetInt(value.(int64))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t}\n\t\treturn nil",
"\tcase reflect.Uint, reflect.Uint64:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tnumber, err := strconv.Atoi(value.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t}\n\t\t\tv.SetUint(uint64(number))\n\t\t\tbreak",
"\t\tcase reflect.Int, reflect.Int64:\n\t\t\tv.SetUint(value.(uint64))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t}\n\t\treturn nil",
"\tcase reflect.Float64:\n\t\tswitch vo.Kind() {\n\t\tcase reflect.String:\n\t\t\tnumber, err := strconv.ParseFloat(value.(string), 64)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid floating number encountered: '\" + value.(string) + \"'\")\n\t\t\t}\n\t\t\tv.SetFloat(number)\n\t\t\tbreak",
"\t\tcase reflect.Float64:\n\t\t\tv.SetFloat(value.(float64))\n\t\t\tbreak",
"\t\tdefault:\n\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t}\n\t\treturn nil",
"\tcase reflect.Struct:\n\t\tty := StructNameT(f.Type)\n\t\tswitch ty {\n\t\tcase \"time.Time\":\n\t\t\tvar no time.Time\n\t\t\tno, err = time.Parse(Config.TimeFormat, value.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\treturn",
"\t\tcase \"database/sql.NullString\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tno := sql.NullString{String: value.(string), Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}\n\t\t\treturn",
"\t\tcase \"database/sql.NullInt64\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tvalid := true\n\t\t\t\tvar number int64 = 0\n\t\t\t\tif value.(string) == \"\" {\n\t\t\t\t\tvalid = false\n\t\t\t\t} else {\n\t\t\t\t\tnumber, err = strconv.ParseInt(value.(string), 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t\t}\n\t\t\t\t}",
"\t\t\t\tno := sql.NullInt64{Int64: number, Valid: valid}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tcase reflect.Int, reflect.Int64:\n\t\t\t\tno := ToNullInt64(value.(int64))\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}\n\t\t\treturn",
"\t\tcase \"database/sql.NullFloat64\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tvalid := true\n\t\t\t\tvar number float64\n\t\t\t\tif value.(string) == \"\" {\n\t\t\t\t\tvalid = false\n\t\t\t\t} else {\n\t\t\t\t\tnumber, err = strconv.ParseFloat(value.(string), 64)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid floating number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t}\n\t\t\t\tno := sql.NullFloat64{Float64: number, Valid: valid}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tcase reflect.Float64:\n\t\t\t\tno := sql.NullFloat64{Float64: value.(float64), Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}\n\t\t\treturn",
"\t\tcase \"database/sql.NullBool\":\n\t\t\tswitch vo.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tyesno := IsTrue(value.(string))\n\t\t\t\tno := sql.NullBool{Bool: yesno, Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tcase reflect.Bool:\n\t\t\t\tno := sql.NullBool{Bool: value.(bool), Valid: true}\n\t\t\t\tv.Set(reflect.ValueOf(no))\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid Type\")\n\t\t\t}",
"\t\t\treturn\n\t\t}",
"\t\t/* Check if the object supports the Scan interface */\n\t\to := StructRecurse(v)\n\t\ttfunc := \"Scan\"\n\t\tobjtrail := []interface{}{o}\n\t\tok, obj := ObjHasFunc(objtrail, tfunc)\n\t\tif ok {\n\t\t\t/* Scan() the value in */\n\t\t\tres, err2 := ObjFunc(obj, tfunc, value)\n\t\t\tif err2 == nil {\n\t\t\t\terr2, ok := res[0].Interface().(error)\n\t\t\t\tif ok {\n\t\t\t\t\terr = err2\n\t\t\t\t}",
"\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\treturn errors.New(fun + \"Variable '\" + fname + \"' is an unknown struct: \" + ty)",
"\tcase reflect.Slice:\n\t\tswitch op {\n\t\tcase STRUCTOP_ADD:\n\t\t\t/* What do we store here? */\n\t\t\tvn := v.Type().String()",
"\t\t\tswitch vn {\n\t\t\tcase \"[]string\":\n\t\t\t\tbreak",
"\t\t\tcase \"[]int\":\n\t\t\t\t/* Input a string or a int? */\n\t\t\t\tswitch vo.Kind() {\n\t\t\t\tcase reflect.String:\n\t\t\t\t\tnumber, err := strconv.Atoi(value.(string))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" Invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t\t}\n\t\t\t\t\tvo = reflect.ValueOf(number)\n\t\t\t\t\tbreak",
"\t\t\t\tcase reflect.Uint, reflect.Uint64:\n\t\t\t\t\tvo = reflect.ValueOf(value.(uint64))\n\t\t\t\t\tbreak",
"\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(fun + \" detected a unsupported type for \" + fname)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}",
"\t\t\tn := reflect.Append(v, vo)\n\t\t\tv.Set(n)\n\t\t\treturn nil",
"\t\tcase STRUCTOP_REMOVE:\n\t\t\t/* What do we store here? */\n\t\t\tvn := v.Type().String()",
"\t\t\t/* Found it? */\n\t\t\tfound := -1",
"\t\t\t/* First, find the item we want to remove */\n\t\t\tfor k := 0; found == -1 && k < v.Len(); k += 1 {\n\t\t\t\tswitch vn {\n\t\t\t\tcase \"[]string\":\n\t\t\t\t\tov := v.Index(k).Interface().(string)\n\t\t\t\t\tif ov == value.(string) {\n\t\t\t\t\t\tfound = k\n\t\t\t\t\t}\n\t\t\t\t\tbreak",
"\t\t\t\tcase \"[]int\", \"[]uint64\":\n\t\t\t\t\tvar ov uint64",
"\t\t\t\t\tswitch vn {\n\t\t\t\t\tcase \"[]int\":\n\t\t\t\t\t\tov = uint64(v.Index(k).Interface().(int))\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tcase \"[]uint64\":\n\t\t\t\t\t\tov = v.Index(k).Interface().(uint64)\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn errors.New(\"Unsupported integer?\")\n\t\t\t\t\t}",
"\t\t\t\t\t/* Input a string or a int? */\n\t\t\t\t\tswitch vo.Kind() {\n\t\t\t\t\tcase reflect.String:\n\t\t\t\t\t\tnumber, err := strconv.Atoi(value.(string))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn errors.New(fun + \"Variable \" + fname + \" invalid number encountered: '\" + value.(string) + \"'\")\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tif uint64(number) == ov {\n\t\t\t\t\t\t\tfound = k\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tcase reflect.Uint:\n\t\t\t\t\t\tnumber := value.(int)",
"\t\t\t\t\t\tif uint64(number) == ov {\n\t\t\t\t\t\t\tfound = k\n\t\t\t\t\t\t}",
"\t\t\t\t\t\tbreak",
"\t\t\t\t\tcase reflect.Uint64:\n\t\t\t\t\t\tnumber := value.(uint64)\n\t\t\t\t\t\tif number == ov {\n\t\t\t\t\t\t\tfound = k\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak",
"\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn errors.New(fun + \" detected a unsupported type for \" + fname)\n\t\t\t\t\t}\n\t\t\t\t\tbreak",
"\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(\"Do not support removing from slice of type \" + vn)\n\t\t\t\t}\n\t\t\t}",
"\t\t\tif found == -1 {\n\t\t\t\treturn errors.New(\"Item not found, thus cannot remove\")\n\t\t\t}",
"\t\t\t/* Create a new slice with all elements except the found one */\n\t\t\tn := v.Slice(0, found)\n\t\t\tn = reflect.AppendSlice(n, v.Slice(found+1, v.Len()))",
"\t\t\t/* Set the slice to the new one, which does not have the item */\n\t\t\tv.Set(n)\n\t\t\treturn nil\n\t\t}",
"\t\t/* Handled nicer above */\n\t\tpanic(\"Cannot apply STRUCTOP_SET to a Slice\")",
"\t/* TODO support reflect.Map */",
"\tdefault:\n\t\tvar k reflect.Kind\n\t\tk = f.Type.Kind()\n\t\treturn errors.New(fun + \"Variable \" + fname + \" Unknown type: \" + k.String())\n\t}\n}",
"// structModA modifies a single field.\n//\n// This is called by StructMod, recursively to be able to support nested structs.\nfunc StructModA(op StructOp, obj interface{}, field string, value interface{}) (done bool, err error) {\n\tfun := \"StructMod() \"",
"\tdone = false",
"\tfield = strings.ToLower(field)",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tdone, err = StructModA(op, StructRecurse(v), field, value)\n\t\t\tif done || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Not this field? */\n\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\tif !v.CanSet() {\n\t\t\terr = errors.New(fun + \"Can't set field '\" + fname + \"'\")\n\t\t\treturn\n\t\t}",
"\t\tdone = true\n\t\terr = StructFieldMod(op, fname, f, v, value)\n\t\treturn\n\t}",
"\treturn\n}",
"// StructMod modifies a single field of a object.\n//\n// Given the object obj, it finds the 'field' in the structure and sets it to the given value.\n//\n// ErrNoRows is returned when no such field was found.\n// Other errors, eg permission errors or inability to set a field can also be returned.\n// An error of nil is returned if the change of the value succeeded.\nfunc StructMod(op StructOp, obj interface{}, field string, value interface{}) (err error) {\n\tdone, err := StructModA(op, obj, field, value)\n\tif err == nil && !done {\n\t\terr = ErrNoRows\n\t\treturn\n\t}",
"\treturn\n}",
"// structVarsA is the recursive portion of StructVars and thus only called by that function\nfunc StructVars(ctx PfCtx, obj interface{}, ptype PType, doignore bool) (vars map[string]string, err error) {\n\tobjtrail := []interface{}{}\n\tvars = make(map[string]string)\n\terr = StructVarsA(ctx, objtrail, obj, ptype, doignore, vars)\n\treturn vars, err\n}",
"// StructVars returns all fields in a struct that can be retrieved or modified, returning a map of strings.\n//\n// StructVars takes an object to inspect and a ptype indicating what permissions the field should satisfy for them to be included.\n//\n// The map consists out of the key being the fieldname and the value being the ToString()'d value of the field.\n//\n// Permissions are tested against the provided ptype and the context.\nfunc StructVarsA(ctx PfCtx, objtrail []interface{}, obj interface{}, ptype PType, doignore bool, vars map[string]string) (err error) {\n\ts, va := StructReflect(obj)",
"\tobjtrail = append([]interface{}{obj}, objtrail...)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\t// ctx.Dbgf(\"StructVars: %s [%s]\", f.Name, f.Type.Kind().String())",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\terr = StructVarsA(ctx, objtrail, StructRecurse(v), ptype, doignore, vars)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\tvar ok bool",
"\t\tok, _, err = StructPermCheck(ctx, ptype, objtrail, PTypeWrap(f))\n\t\t// ctx.Dbgf(\"StructVars: %s - permcheck: %s, err: %v\", f.Name, YesNo(ok), err)\n\t\tif err != nil {\n\t\t\tskipfailperm := f.Tag.Get(\"pfskipfailperm\")\n\t\t\tif skipfailperm == \"\" {\n\t\t\t\tctx.Dbgf(\"StructVars: %s - permcheck: %s, err: %s\", f.Name, YesNo(ok), err.Error())\n\t\t\t}\n\t\t\tcontinue\n\t\t}",
"\t\tif !ok && ttype != \"ptr\" && ttype != \"struct\" {\n\t\t\t// oname := StructNameObjTrail(objtrail)\n\t\t\t// ctx.Dbg(\"NOT SHOWING: field = %s, ttype = %s\", oname+\":\"+fname, ttype)\n\t\t\tcontinue\n\t\t}",
"\t\tvars[fname] = ttype\n\t}",
"\terr = nil\n\treturn\n}",
"// StructDetails_Options defines options to apply when checking StructDetails\ntype StructDetails_Options int",
"const (\n\tSD_None = 0 /* No Options */\n\tSD_Perms_Check StructDetails_Options = 0 << iota /* Check Permissions */\n\tSD_Perms_Ignore /* Ignore Permissions */\n\tSD_Tags_Require /* Require Tags */\n\tSD_Tags_Ignore /* Ignore Tags */\n)",
"// structDetailsA is the recursive portion of StructDetails, see that function for more details\nfunc StructDetailsA(ctx PfCtx, obj interface{}, field string, opts StructDetails_Options) (ftype string, fname string, fvalue string, err error) {\n\tcheckperms := false\n\tif opts&SD_Perms_Check > 0 {\n\t\tcheckperms = true\n\t}",
"\trequiretags := false\n\tif opts&SD_Tags_Require > 0 {\n\t\trequiretags = true\n\t}",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname = f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Ignore the field completely? */\n\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tif fname == field {\n\t\t\t\treturn \"ignore\", \"\", \"\", errors.New(\"Field is ignored\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tftype, fname, fvalue, err = StructDetailsA(ctx, StructRecurse(v), field, opts)\n\t\t\tif ftype != \"\" || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif requiretags && f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Wrong field, skip it */\n\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\tif checkperms {\n\t\t\tok := true\n\t\t\tpermstr := f.Tag.Get(\"pfset\")",
"",
"\t\t\tok, err = ctx.CheckPermsT(\"StructDetails(\"+fname+\")\", permstr)\n\t\t\tif !ok {\n\t\t\t\treturn \"\", \"\", \"\", err\n\t\t\t}\n\t\t}",
"\t\treturn \"string\", fname, ToString(v.Interface()), nil\n\t}",
"\treturn \"\", \"\", \"\", nil\n}",
"// StructDetails returns the details of a structure's field.\n//\n// It determines the type of the field and the string value of the field.\n//\n// The opts can be used to influence if permission checking needs to be done\n// and if tags are required to be present for the field to be checked.\nfunc StructDetails(ctx PfCtx, obj interface{}, field string, opts StructDetails_Options) (ftype string, fname string, fvalue string, err error) {\n\tfield = strings.ToLower(field)",
"\tftype, fname, fvalue, err = StructDetailsA(ctx, obj, field, opts)\n\tif err == nil && ftype == \"\" {\n\t\treturn \"unknown\", \"\", \"\", errors.New(\"Unknown Field: \" + field + \" (StructDetails)\")\n\t}",
"\treturn\n}",
"// structTagA is the recursive portion of StructTag, see that function for details\nfunc StructTagA(obj interface{}, field string, tag string) (val string, err error) {\n\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tval, err = StructTagA(StructRecurse(v), field, tag)\n\t\t\tif err != nil || val != \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\tval = f.Tag.Get(tag)\n\t\treturn\n\t}",
"\treturn \"\", nil\n}",
"// StructTag retrieves the requested tag from a field in a structure.\n//\n// Any type of object can be provided, it will be recursed incase of embedded structs.\n//\n// The field indicates the name of the structure's field.\n// The tag indicates which tag to get for that field.\n//\n// The value returned is the content of the tag for the requested field.\nfunc StructTag(obj interface{}, field string, tag string) (val string, err error) {\n\tfield = strings.ToLower(field)",
"\tval, err = StructTagA(obj, field, tag)\n\tif err == nil && val == \"\" {\n\t\treturn \"\", errors.New(\"Unknown Field: \" + field + \" (StructTag)\")\n\t}",
"\treturn\n}",
"// structMenuA is the recursive portion of StructMenu\n//\n// See StructMenu for more details.\nfunc StructMenuA(ctx PfCtx, subjects []string, objtrail []interface{}, obj interface{}, onlyslices bool, fun PfFunc, isedit bool, nargs int) (menu PfMenu, err error) {\n\t/* Prepend this object to the trail */\n\tobjtrail = append([]interface{}{obj}, objtrail...)",
"\ts, va := StructReflect(obj)",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tm, err := StructMenuA(ctx, subjects, objtrail, StructRecurse(v), onlyslices, fun, isedit, nargs)\n\t\t\tif err != nil {\n\t\t\t\treturn PfMenu{}, err\n\t\t\t}",
"\t\t\tmenu.Add(m.M...)\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Ignore slices when we don't want them, others if we only want slices */\n\t\tif (ttype == \"slice\" && onlyslices == false) || (ttype != \"slice\" && onlyslices == true) {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Options from the Tag of the structure */\n\t\tlabel := f.Tag.Get(\"label\")\n\t\tif label != \"\" {\n\t\t\t/* Only translate when the label is specifically set */\n\t\t\tlabel = TranslateObj(ctx, objtrail, label)\n\t\t} else {\n\t\t\tlabel = f.Name\n\t\t}",
"\t\thint := f.Tag.Get(\"hint\")\n\t\tif hint != \"\" {\n\t\t\t/* Only translate when the hint is specifically set */\n\t\t\thint = TranslateObj(ctx, objtrail, hint)\n\t\t}",
"\t\t/* Default description to the label */\n\t\tdesc := label",
"\t\t/* Append the hint to the description */\n\t\tif hint != \"\" {\n\t\t\tdesc += \" - \" + hint\n\t\t}",
"\t\t/* Ignore the field completely? */\n\t\tignore := f.Tag.Get(\"pfignore\")\n\t\tif ignore == \"yes\" {\n\t\t\tcontinue\n\t\t}",
"\t\tvar perms Perm\n\t\tvar tag string",
"\t\tif isedit {\n\t\t\ttag = \"pfset\"\n\t\t} else {\n\t\t\ttag = \"pfget\"\n\t\t}",
"\t\tset := f.Tag.Get(tag)",
"\t\tperms,err = FromString(set)",
"\t\tif err != nil {\n\t\t\treturn\n\t\t}",
"\t\tif perms == PERM_NOTHING {\n\t\t\t/* Default permissions is to allow getting/setting of anything */\n\t\t\tperms = PERM_NONE\n\t\t}",
"\t\tvar ok bool\n\t\tok, _ = ctx.CheckPerms(\"StructMenu(\"+fname+\")\", perms)\n\t\tif !ok {\n\t\t\t/* Also change to 'ok, err' above */\n\t\t\t/* Dbgf(\"StructMenu(%s) Skipping (tag: %s), err: %s\", fname, tag, err.Error()) */\n\t\t\tcontinue\n\t\t}",
"\t\t/* Initial subjects */\n\t\tsubj := subjects",
"\t\tif isedit {\n\t\t\totype := \"\"",
"\t\t\tswitch ttype {\n\t\t\tcase \"bool\":\n\t\t\t\totype = \"#bool\"\n\t\t\t\tbreak",
"\t\t\tcase \"int\":\n\t\t\t\totype = \"#int\"\n\t\t\t\tbreak",
"\t\t\tcase \"file\":\n\t\t\t\totype = \"#file\"\n\t\t\t\totype += \"#\" + f.Tag.Get(\"pfmaximagesize\")",
"\t\t\t\tb64 := f.Tag.Get(\"pfb64\")\n\t\t\t\totype += \"#\" + NormalizeBoolean(b64)\n\t\t\t\tbreak",
"\t\t\tcase \"string\", \"text\", \"tel\":\n\t\t\t\totype = \"#string\"\n\t\t\t\tbreak",
"\t\t\tcase \"time\":\n\t\t\t\totype = \"#time\"\n\t\t\t\tbreak",
"\t\t\tcase \"struct\":\n\t\t\t\tbreak",
"\t\t\tcase \"slice\":\n\t\t\t\tbreak",
"\t\t\tcase \"map\":\n\t\t\t\tbreak",
"\t\t\tcase \"ptr\":\n\t\t\t\tbreak",
"\t\t\tdefault:\n\t\t\t\tpanic(\"Unknown Type for field \" + fname + \", type \" + ttype)\n\t\t\t}",
"\t\t\tsubj = append(subj, fname+otype)\n\t\t}",
"\t\tvar m PfMEntry\n\t\tm.Cmd = fname\n\t\tm.Fun = fun\n\t\tm.Args_min = nargs\n\t\tm.Args_max = nargs\n\t\tm.Args = subj\n\t\tm.Perms = perms\n\t\tm.Desc = desc",
"\t\tmenu.Add(m)\n\t}",
"\treturn menu, nil\n}",
"// StructMenu can create \"get\", \"set\", \"add\" and \"remove\" CLI menus\n// from a given structure.\n//\n// The subjects parameter indicates the field(s) that indicates what\n// should be provided as an argument to select that specific object.\n//\n// The object is an example object (just the structure, no values needed)\n// that has a set of fields with tags. The tags are used to retrieve the\n// labels and descriptions for the field, but also the permissions needed\n// to configure that field.\n//\n// onlyslices is used to switch between a 'get'/'set' menu and a 'add'/'remove' menu.\n// When onlyslices is true only fields that are slices are listed, these will\n// require an 'add'/'remove' construct instead of being able to be directly 'set' or 'get'.\n//\n// When a function is provided, the menu becomes a 'set' or add/remove menu (for slices).\n// When no function is provided the resulting menu is a 'get' menu.\n// The permissions for set/get are adhered to.\n//\n// See the example for a minimal example. The User portion of Pitchfork makes a good\n// full example on how this code is used, see lib/user.go user_get/user_set etc.\nfunc StructMenu(ctx PfCtx, subjects []string, obj interface{}, onlyslices bool, fun PfFunc) (menu PfMenu, err error) {\n\tvar isedit bool",
"\t/* Select the Object */\n\tctx.SelectObject(&obj)",
"\t/* Number of subjects */\n\tnargs := len(subjects)",
"\t/* Edit or not? */\n\tif fun != nil {\n\t\tisedit = true",
"\t\t/* Edit's require one more argument */\n\t\tnargs++\n\t} else {\n\t\tfun = structGet\n\t}",
"\t/* Recursive call */\n\tobjtrail := []interface{}{}\n\treturn StructMenuA(ctx, subjects, objtrail, obj, onlyslices, fun, isedit, nargs)\n}",
"// structGetA is the recursive part of StructGet.\nfunc structGetA(ctx PfCtx, obj interface{}, field string) (done bool, err error) {\n\ts, va := StructReflect(obj)",
"\tdone = false",
"\tif s.Kind() == reflect.Interface {\n\t\treturn structGetA(ctx, StructRecurse(va), field)\n\t}",
"\tif s.Kind() != reflect.Struct {\n\t\terr = errors.New(\"Error: parameter is not a struct/interface but \" + s.String() + \" (structGet)\")\n\t\treturn\n\t}",
"\tfor i := 0; i < s.NumField(); i++ {\n\t\tf := s.Field(i)\n\t\tv := va.Field(i)",
"\t\tttype, dorecurse, compound := PfType(f, v, true)\n\t\tif ttype == \"ignore\" {\n\t\t\tcontinue\n\t\t}",
"\t\tif dorecurse {\n\t\t\tdone, err = structGetA(ctx, StructRecurse(v), field)\n\t\t\tif done || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}",
"\t\tif compound {\n\t\t\tcontinue\n\t\t}",
"\t\t/* No tags, then ignore it */\n\t\tif f.Tag == \"\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Column/fieldname in SQL Table */\n\t\tfname := f.Tag.Get(\"pfcol\")\n\t\tif fname == \"\" {\n\t\t\tfname = strings.ToLower(f.Name)\n\t\t}",
"\t\t/* Wrong field -> next! */\n\t\tif fname != field {\n\t\t\tcontinue\n\t\t}",
"\t\t/* Ignore the field completely? */\n\t\tignore := f.Tag.Get(\"pfignore\")\n\t\tif ignore == \"yes\" {\n\t\t\tcontinue\n\t\t}",
"\t\t/*\n\t\t * Note: structGet does not check permissions,\n\t\t * it is only used by StructMenu() which does\n\t\t * check for permissions\n\t\t */\n\t\tstr := ToString(v.Interface())\n\t\tctx.OutLn(str)",
"\t\tdone = true\n\t\terr = nil\n\t\treturn\n\t}",
"\treturn\n}",
"// Create a \"get\" menu from a struct -- helper function of StructMenu.\nfunc structGet(ctx PfCtx, args []string) (err error) {\n\tobj := ctx.SelectedObject()",
"\tif obj == nil {\n\t\treturn errors.New(\"No object selected\")\n\t}",
"\tfield := ctx.GetLastPart()",
"\tdone, err := structGetA(ctx, obj, field)\n\tif err == nil && !done {\n\t\terr = errors.New(\"Unknown property\")\n\t}",
"\treturn\n}",
"// ToString converts any type of object to a string representation.\nfunc ToString(v interface{}) (str string) {\n\ts, _ := StructReflect(v)",
"\tswitch s.Kind() {",
"\tcase reflect.String:\n\t\treturn v.(string)",
"\tcase reflect.Bool:\n\t\treturn YesNo(v.(bool))",
"\tcase reflect.Int:\n\t\treturn strconv.Itoa(v.(int))",
"\tcase reflect.Uint:\n\t\treturn strconv.FormatUint(uint64(v.(uint)), 10)",
"\tcase reflect.Int64:\n\t\treturn strconv.FormatInt(v.(int64), 10)",
"\tcase reflect.Uint64:\n\t\treturn strconv.FormatUint(v.(uint64), 10)",
"\tcase reflect.Float64:\n\t\treturn strconv.FormatFloat(v.(float64), 'E', -1, 64)",
"\tcase reflect.Struct:\n\t\tty := StructNameT(s)",
"\t\tswitch ty {\n\t\tcase \"time.Time\":\n\t\t\tno := v.(time.Time)\n\t\t\treturn no.Format(Config.TimeFormat)",
"\t\tcase \"database/sql.NullString\":\n\t\t\tno := v.(sql.NullString)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.String)",
"\t\tcase \"database/sql.NullInt64\":\n\t\t\tno := v.(sql.NullInt64)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.Int64)",
"\t\tcase \"database/sql.NullFloat64\":\n\t\t\tno := v.(sql.NullFloat64)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.Float64)",
"\t\tcase \"database/sql.NullBool\":\n\t\t\tno := v.(sql.NullBool)\n\t\t\tif !no.Valid {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn ToString(no.Bool)",
"\t\tdefault:\n\t\t\t/* Try if the object has a String() function */\n\t\t\ttfunc := \"String\"\n\t\t\tobjtrail := []interface{}{v}\n\t\t\tok, obj := ObjHasFunc(objtrail, tfunc)\n\t\t\tif ok {\n\t\t\t\ts, err := ObjFuncStr(obj, tfunc)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn s\n\t\t\t\t}\n\t\t\t}",
"\t\t\tpanic(\"ToString() Unhandled Struct Type '\" + ty + \"' : \" + s.String())\n\t\t}\n\t}",
"\tpanic(\"ToString() Unhandled Type: \" + s.String())\n}",
"// ObjFuncI retains a object.\ntype ObjFuncI struct {\n\tobj interface{}\n}",
"// ObjHasFunc is used to determine of an object has the given function,\n// returning the (embedded) object that has the function\n//\n// An objecttrail consisting of one or more objects is passed in, thus\n// allowing a function to be found in a nested set of objects.\n//\n// This call should be used before ObjFunc to ensure the function\n// has the given object, and to select the correct object.\nfunc ObjHasFunc(objtrail []interface{}, fun string) (ok bool, obj ObjFuncI) {\n\tok = false",
"\tfor _, ob := range objtrail {\n\t\to := reflect.ValueOf(ob)",
"\t\tif o.IsValid() {\n\t\t\tf := o.MethodByName(fun)\n\t\t\tif f.IsValid() {\n\t\t\t\tok = true\n\t\t\t\tobj.obj = ob\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tErrf(\"Not a valid object: %#v\", obj)\n\t\t}\n\t}",
"\treturn\n}",
"// ObjFunc calls, when available, a function in an object and returns it's result\n//\n// The 'fun' is retrieved from the given object, as typically found with ObjHasFunc.\n// The function is then verified to be able to accept the parameters specified by params.\n// And the function is then called dynamically.\n//\n// One major use-case is the Translate function of objects, where we typically do\n// not know what object we will be calling that function on.\nfunc ObjFunc(obj ObjFuncI, fun string, params ...interface{}) (result []reflect.Value, err error) {\n\tresult = nil\n\terr = nil",
"\to := reflect.ValueOf(obj.obj)\n\tif !o.IsValid() {\n\t\terr = errors.New(\"Not a valid object\")\n\t\treturn\n\t}",
"\tf := o.MethodByName(fun)\n\tif !f.IsValid() {\n\t\terr = errors.New(\"Unknown Function \" + fun)\n\t\treturn\n\t}",
"\tpnum := f.Type().NumIn()\n\tif (f.Type().IsVariadic() && len(params) < pnum) || (!f.Type().IsVariadic() && len(params) != pnum) {\n\t\tvtxt := \"\"\n\t\tif f.Type().IsVariadic() {\n\t\t\tvtxt = \" [note: variadic]\"\n\t\t}\n\t\terr = errors.New(\"Wrong amount of parameters, got: \" + strconv.Itoa(len(params)) + \", need: \" + strconv.Itoa(pnum) + vtxt)\n\t\tpanic(\"Need more\")\n\t}",
"\tin := make([]reflect.Value, len(params))",
"\tfor k, param := range params {\n\t\t/* Avoid a null Value */\n\t\tif param == nil {\n\t\t\tin[k] = reflect.ValueOf(¶m).Elem()\n\t\t} else {\n\t\t\tin[k] = reflect.ValueOf(param)\n\t\t}\n\t}",
"\tresult = f.Call(in)\n\treturn\n}",
"// ObjFuncIface calls a function of an object and returns the result of an interface.\n//\n// See ObjFunc for more details on the parameters.\nfunc ObjFuncIface(obj ObjFuncI, fun string, params ...interface{}) (iface interface{}, err error) {\n\tres, err := ObjFunc(obj, fun, params...)",
"\tif err == nil {\n\t\tiface = res[0].Interface()\n\t} else {\n\t\tiface = nil\n\t}",
"\treturn\n}",
"// ObjFuncStr calls a function of an object and returns a string.\n//\n// When the returned type of the called function is not a string,\n// this code will return a string indicating that in the string.\n// Similary the string will be filled with a notion that the call failed.\n// Next to having a non-nil error return.\n//\n// See ObjFunc for more details on the parameters.\nfunc ObjFuncStr(obj ObjFuncI, fun string, params ...interface{}) (str string, err error) {\n\tres, err := ObjFunc(obj, fun, params...)",
"\tif err == nil {\n\t\tif res[0].Kind() == reflect.String {\n\t\t\tstr = res[0].String()\n\t\t} else {\n\t\t\tstr = fun + \"()-not-a-string\"\n\t\t}\n\t} else {\n\t\tstr = fun + \"()-failed\"\n\t}",
"\treturn\n}",
"// objPermCheck calls custom PermCheck function on an object and determines\n// if one has access and is allowed to edit or not.\n//\n// The ptype is used for the permission check to determine if read or write access is needed.\n// Per-application permissions could be more strict and be full CRUD-style.\n//\n// The return of 'ok' indicates that it is allowed to access the field.\n// The allowedit indicates if the field is allowed to be edited/modified.\n// The error indicates whether anything failed, nil indicates success.\n//\n// This function is used by StructPermCheck.\nfunc ObjPermCheck(ctx PfCtx, obj ObjFuncI, ptype PType, f PTypeField) (ok bool, allowedit bool, err error) {\n\tres, err := ObjFunc(obj, \"PermCheck\", ctx, ptype, f)",
"\tif err == nil {\n\t\tvar varok bool",
"\t\tok = res[0].Interface().(bool)\n\t\tallowedit = res[1].Interface().(bool)\n\t\terr, varok = res[2].Interface().(error)\n\t\tif !varok {\n\t\t\terr = nil\n\t\t}\n\t} else {\n\t\tok = false\n\t\tallowedit = false\n\t}",
"\treturn\n}",
"// StructPermCheck checks the permissions of a struct,\n// and determines if one has acccess and is allowed to edit.\n//\n// The ptype allows specifying of CRUD-style (Create/Read/Update/Delete) permissions to check for.\n// The objtrail is passed in, to allow a surrounding object to be used for Permission checking.\n// The PermCheck function of the first object in the trail is used for permission checks next to\n// the pitchfork pfget/pfset permissions.\n//\n// The f parameter is the field we are checking permissions for.\n//\n// The return of 'ok' indicates that it is allowed to access the field.\n// The allowedit indicates if the field is allowed to be edited/modified.\n// The error indicates whether anything failed, nil indicates success.\nfunc StructPermCheck(ctx PfCtx, ptype PType, objtrail []interface{}, f PTypeField) (ok bool, allowedit bool, err error) {\n\tswitch ptype {\n\tcase PTYPE_CREATE, PTYPE_UPDATE:\n\t\tallowedit = true\n\t\tbreak",
"\tcase PTYPE_READ, PTYPE_DELETE:\n\t\tallowedit = false\n\t\tbreak",
"\tdefault:\n\t\tpanic(\"Unknown ptype\")\n\t}",
"\t/* Check Application specific permissions */\n\tapp_perms, obj := ObjHasFunc(objtrail, \"PermCheck\")\n\tif app_perms {\n\t\tok, allowedit, err = ObjPermCheck(ctx, obj, ptype, f)",
"\t\tif err == nil && !ok && allowedit {\n\t\t\t/* Retry in read mode */\n\t\t\tptype = PTYPE_READ\n\t\t\tok, allowedit, err = ObjPermCheck(ctx, obj, ptype, f)\n\t\t}",
"\t\t/* Errors or denies give a direct answer */\n\t\tif err != nil || !ok {\n\t\t\treturn\n\t\t}\n\t}",
"\t/* If there is a Pitchfork tag it also gets to make a decision */\n\ttag := \"pfget\"\n\tif allowedit {\n\t\ttag = \"pfset\"\n\t}",
"\tpermstr := f.Tag.Get(tag)",
"\tif !app_perms || permstr != \"\" {\n\t\tok, err = ctx.CheckPermsT(\"StructPermCheck(\"+f.Name+\"/\"+tag+\"/\"+permstr+\")\", permstr)\n\t\tif !ok && allowedit {\n\t\t\tallowedit = false\n\t\t\ttag = \"pfget\"\n\t\t\tpermstr := f.Tag.Get(tag)",
"\t\t\t/* Use the fail for pfset, if no pfget is defined and pfset errored */\n\t\t\tif permstr == \"\" && err != nil {\n\t\t\t\treturn\n\t\t\t}",
"\t\t\t/* Fall back */\n\t\t\tok, err = ctx.CheckPermsT(\"StructPermCheck(\"+f.Name+\"/get/\"+permstr+\")\", permstr)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}",
"\treturn\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1336, 1537], "buggy_code_start_loc": [947, 1355], "filenames": ["lib/ctx.go", "lib/struct.go"], "fixing_code_end_loc": [1336, 1538], "fixing_code_start_loc": [947, 1356], "message": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:secluded:trident:1.4.6:rc1:*:*:*:*:*:*", "matchCriteriaId": "52F21E24-C1E2-4E41-B00C-FB5441CCD7CF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Pitchfork version 1.4.6 RC1 contains an Improper Privilege Management vulnerability in Trident Pitchfork components that can result in A standard unprivileged user could gain system administrator permissions within the web portal.. This attack appear to be exploitable via The user must be able to login, and could edit their profile and set the \"System Administrator\" permission to \"yes\" on themselves.. This vulnerability appears to have been fixed in 1.4.6 RC2."}, {"lang": "es", "value": "Pitchfork, en su versi\u00f3n 1.4.6 RC1, contiene una vulnerabilidad de gesti\u00f3n incorrecta de privilegios en los componentes Trident Pitchfork que puede resultar en que un usuario est\u00e1ndar sin privilegios obtenga permisos de administrador en el portal web. El usuario debe ser capaz de iniciar sesi\u00f3n y podr\u00eda editar su perfil y establecer el permiso \"System Administrator\" en \"yes\" para s\u00ed mismo. La vulnerabilidad parece haber sido solucionada en la versi\u00f3n 1.4.6 RC2."}], "evaluatorComment": null, "id": "CVE-2018-1000133", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.6, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-03-16T14:29:44.847", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/commit/9fd07cbe4f93e1367e142016e9a205366680dd54"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/tridentli/pitchfork/issues/168"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/tridentli/trident/releases/tag/DEV_1.4.6-RC2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://thomas-ward.net/security-advisories/trident-trusted-communications-platform-privilege-escalation-issue-advisory/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-269"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/tridentli/pitchfork/commit/33549f15707801099e1253dd5e79369bd48eb59b"}, "type": "CWE-269"}
| 312
|
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-2012\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / Media Tools sub-project\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/internal/media_dev.h>\n#include <gpac/base_coding.h>\n#include <gpac/mpeg4_odf.h>\n#include <gpac/constants.h>\n#include <gpac/maths.h>\n#include <gpac/internal/ietf_dev.h>",
"#ifndef GPAC_DISABLE_ISOM",
"void gf_media_get_sample_average_infos(GF_ISOFile *file, u32 Track, u32 *avgSize, u32 *MaxSize, u32 *TimeDelta, u32 *maxCTSDelta, u32 *const_duration, u32 *bandwidth)\n{\n\tu32 i, count, ts_diff;\n\tu64 prevTS, tdelta;\n\tDouble bw;\n\tGF_ISOSample *samp;",
"\t*avgSize = *MaxSize = 0;\n\t*TimeDelta = 0;\n\t*maxCTSDelta = 0;\n\tbw = 0;\n\tprevTS = 0;\n\ttdelta = 0;",
"\tcount = gf_isom_get_sample_count(file, Track);\n\tif (!count) return;\n\t*const_duration = 0;",
"\tfor (i=0; i<count; i++) {\n\t\tsamp = gf_isom_get_sample_info(file, Track, i+1, NULL, NULL);\n\t\tif (!samp) break;\n\t\t\n\t\t//get the size\n\t\t*avgSize += samp->dataLength;\n\t\tif (*MaxSize < samp->dataLength) *MaxSize = samp->dataLength;\n\t\tts_diff = (u32) (samp->DTS+samp->CTS_Offset - prevTS);\n\t\t//get the time\n\t\ttdelta += ts_diff;",
"\t\tif (i==1) {\n\t\t\t*const_duration = ts_diff;\n\t\t} else if ( (i<count-1) && (*const_duration != ts_diff) ) {\n\t\t\t*const_duration = 0;\n\t\t}",
"\t\tprevTS = samp->DTS+samp->CTS_Offset;\n\t\tbw += 8*samp->dataLength;",
"\t\t//get the CTS delta\n\t\tif ((samp->CTS_Offset>=0) && ((u32)samp->CTS_Offset > *maxCTSDelta))\n\t\t\t*maxCTSDelta = samp->CTS_Offset;\n\t\tgf_isom_sample_del(&samp);\n\t}\n\tif (count>1) *TimeDelta = (u32) (tdelta/ (count-1) );\n\telse *TimeDelta = (u32) tdelta;\n\t*avgSize /= count;\n\tbw *= gf_isom_get_media_timescale(file, Track);\n\tbw /= (s64) gf_isom_get_media_duration(file, Track);\n\tbw /= 1000;\n\t(*bandwidth) = (u32) (bw+0.5);",
"\t//delta is NOT an average, we need to know exactly how many bits are\n\t//needed to encode CTS-DTS for ANY samples\n}",
"\n#ifndef GPAC_DISABLE_ISOM_HINTING",
"/*RTP track hinter*/\nstruct __tag_isom_hinter\n{\n\tGF_ISOFile *file;\n\t/*IDs are kept for mp4 hint sample building*/\n\tu32 TrackNum, TrackID, HintTrack, HintID;\n\t/*current Hint sample and associated RTP time*/\n\tu32 HintSample, RTPTime;",
"\t/*track has composition time offset*/\n\tBool has_ctts;\n\t/*remember if first SL packet in RTP packet is RAP*/\n\tu8 SampleIsRAP;\n\tu32 base_offset_in_sample;\n\tu32 OrigTimeScale;\n\t/*rtp builder*/\n\tGP_RTPPacketizer *rtp_p;",
"\tu32 bandwidth, nb_chan;",
"\t/*NALU size for H264/AVC*/\n\tu32 avc_nalu_size;",
"\t/*stats*/\n\tu32 TotalSample, CurrentSample;\n};",
"\n/*\n\toffset for group ID for hint tracks in SimpleAV mode when all media data\n\tis copied to the hint track (no use interleaving hint and original in this case)\n\tthis offset is applied internally by the track hinter. Thus you shouldn't\n\tspecify a GroupID >= OFFSET_HINT_GROUP_ID if you want the lib to perform efficient\n\tinterleaving in any cases (referenced or copied media)\n*/\n#define OFFSET_HINT_GROUP_ID\t0x8000",
"void InitSL_RTP(GF_SLConfig *slc)\n{\n\tmemset(slc, 0, sizeof(GF_SLConfig));\n\tslc->tag = GF_ODF_SLC_TAG;\n\tslc->useTimestampsFlag = 1;\n\tslc->timestampLength = 32;\n}",
"void InitSL_NULL(GF_SLConfig *slc)\n{\n\tmemset(slc, 0, sizeof(GF_SLConfig));\n\tslc->tag = GF_ODF_SLC_TAG;\n\tslc->predefined = 0x01;\n}",
"",
"void MP4T_OnPacketDone(void *cbk, GF_RTPHeader *header)\n{\n\tu8 disposable;\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!tkHint || !tkHint->HintSample) return;\n\tassert(header->TimeStamp == tkHint->RTPTime);",
"\tdisposable = 0;\n\tif (tkHint->avc_nalu_size) {\n\t\tdisposable = tkHint->rtp_p->avc_non_idr ? 1 : 0;\n\t}\n\t/*for all other, assume that CTS=DTS means B-frame -> disposable*/\n\telse if (tkHint->has_ctts && (tkHint->rtp_p->sl_header.compositionTimeStamp==tkHint->rtp_p->sl_header.decodingTimeStamp)) {\n\t\tdisposable = 1;\n\t}",
"\tgf_isom_rtp_packet_set_flags(tkHint->file, tkHint->HintTrack, 0, 0, header->Marker, disposable, 0);\n}",
"\nvoid MP4T_OnDataRef(void *cbk, u32 payload_size, u32 offset_from_orig)\n{\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!tkHint || !payload_size) return;",
"\t/*add reference*/\n\tgf_isom_hint_sample_data(tkHint->file, tkHint->HintTrack, tkHint->TrackID,\n\t tkHint->CurrentSample, (u16) payload_size, offset_from_orig + tkHint->base_offset_in_sample,\n\t NULL, 0);\n}",
"void MP4T_OnData(void *cbk, u8 *data, u32 data_size, Bool is_header)\n{\n\tu8 at_begin;\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!data_size) return;",
"\tat_begin = is_header ? 1 : 0;\n\tif (data_size <= 14) {\n\t\tgf_isom_hint_direct_data(tkHint->file, tkHint->HintTrack, data, data_size, at_begin);\n\t} else {\n\t\tgf_isom_hint_sample_data(tkHint->file, tkHint->HintTrack, tkHint->HintID, 0, (u16) data_size, 0, data, at_begin);\n\t}\n}",
"\nvoid MP4T_OnNewPacket(void *cbk, GF_RTPHeader *header)\n{\n\ts32 res;\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!tkHint) return;",
"\tres = (s32) (tkHint->rtp_p->sl_header.compositionTimeStamp - tkHint->rtp_p->sl_header.decodingTimeStamp);\n\tassert( !res || tkHint->has_ctts);\n\t/*do we need a new sample*/\n\tif (!tkHint->HintSample || (tkHint->RTPTime != header->TimeStamp)) {\n\t\t/*close current sample*/\n\t\tif (tkHint->HintSample) gf_isom_end_hint_sample(tkHint->file, tkHint->HintTrack, tkHint->SampleIsRAP);",
"\t\t/*start new sample: We use DTS as the sampling instant (RTP TS) to make sure\n\t\tall packets are sent in order*/\n\t\tgf_isom_begin_hint_sample(tkHint->file, tkHint->HintTrack, 1, header->TimeStamp-res);\n\t\ttkHint->HintSample ++;\n\t\ttkHint->RTPTime = header->TimeStamp;\n\t\ttkHint->SampleIsRAP = tkHint->rtp_p->sl_config.hasRandomAccessUnitsOnlyFlag ? 1 : tkHint->rtp_p->sl_header.randomAccessPointFlag;\n\t}\n\t/*create an RTP Packet with the appropriated marker flag - note: the flags are temp ones,\n\tthey are set when the full packet is signaled (to handle multi AUs per RTP)*/\n\tgf_isom_rtp_packet_begin(tkHint->file, tkHint->HintTrack, 0, 0, 0, header->Marker, header->PayloadType, 0, 0, header->SequenceNumber);\n\t/*Add the delta TS to make sure RTP TS is indeed the CTS (sampling time)*/\n\tif (res) gf_isom_rtp_packet_set_offset(tkHint->file, tkHint->HintTrack, res);\n}",
"\nGF_EXPORT\nGF_RTPHinter *gf_hinter_track_new(GF_ISOFile *file, u32 TrackNum,\n u32 Path_MTU, u32 max_ptime, u32 default_rtp_rate, u32 flags, u8 PayloadID,\n Bool copy_media, u32 InterleaveGroupID, u8 InterleaveGroupPriority, GF_Err *e)\n{",
"\tGF_SLConfig my_sl;\n\tu32 descIndex, MinSize, MaxSize, avgTS, streamType, codecid, const_dur, nb_ch, maxDTSDelta;\n\tu8 OfficialPayloadID;\n\tu32 TrackMediaSubType, TrackMediaType, hintType, nbEdts, required_rate, force_dts_delta, avc_nalu_size, PL_ID, bandwidth, IV_length, KI_length;\n\tconst char *url, *urn;\n\tchar *mpeg4mode;\n\tBool is_crypted, has_mpeg4_mapping;\n\tGF_RTPHinter *tmp;\n\tGF_ESD *esd;",
"\t*e = GF_BAD_PARAM;\n\tif (!file || !TrackNum || !gf_isom_get_track_id(file, TrackNum)) return NULL;",
"\tif (!gf_isom_get_sample_count(file, TrackNum)) {\n\t\t*e = GF_OK;\n\t\treturn NULL;\n\t}\n\t*e = GF_NOT_SUPPORTED;\n\tnbEdts = gf_isom_get_edits_count(file, TrackNum);\n\tif (nbEdts>1) {\n\t\tu64 et, sd, mt;\n\t\tGF_ISOEditType em;\n\t\tgf_isom_get_edit(file, TrackNum, 1, &et, &sd, &mt, &em);\n\t\tif ((nbEdts>2) || (em!=GF_ISOM_EDIT_EMPTY)) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Cannot hint track whith EditList\\n\"));\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tif (nbEdts) gf_isom_remove_edits(file, TrackNum);",
"\tif (!gf_isom_is_track_enabled(file, TrackNum)) return NULL;",
"\t/*by default NO PL signaled*/\n\tPL_ID = 0;\n\tOfficialPayloadID = 0;\n\tforce_dts_delta = 0;\n\tstreamType = 0;\n\tmpeg4mode = NULL;\n\trequired_rate = 0;\n\tis_crypted = 0;\n\tIV_length = KI_length = 0;\n\tcodecid = 0;\n\tnb_ch = 0;\n\tavc_nalu_size = 0;\n\thas_mpeg4_mapping = 1;\n\tconst_dur = 0;\n\tbandwidth=0;\n\tTrackMediaType = gf_isom_get_media_type(file, TrackNum);",
"\t/*for max compatibility with QT*/\n\tif (!default_rtp_rate) default_rtp_rate = 90000;",
"\t/*timed-text is a bit special, we support multiple stream descriptions & co*/\n\tif ( (TrackMediaType==GF_ISOM_MEDIA_TEXT) || (TrackMediaType==GF_ISOM_MEDIA_SUBT)) {\n\t\thintType = GF_RTP_PAYT_3GPP_TEXT;\n\t\tcodecid = GF_CODECID_TEXT_MPEG4;\n\t\tstreamType = GF_STREAM_TEXT;\n\t\t/*fixme - this works cos there's only one PL for text in mpeg4 at the current time*/\n\t\tPL_ID = 0x10;\n\t} else {\n\t\tif (gf_isom_get_sample_description_count(file, TrackNum) > 1) return NULL;",
"\t\tTrackMediaSubType = gf_isom_get_media_subtype(file, TrackNum, 1);\n\t\tswitch (TrackMediaSubType) {\n\t\tcase GF_ISOM_SUBTYPE_MPEG4_CRYP:\n\t\t\tis_crypted = 1;\n\t\tcase GF_ISOM_SUBTYPE_MPEG4:\n\t\t\tesd = gf_isom_get_esd(file, TrackNum, 1);\n\t\t\thintType = GF_RTP_PAYT_MPEG4;\n\t\t\tif (esd && esd->decoderConfig) {\n\t\t\t\tstreamType = esd->decoderConfig->streamType;\n\t\t\t\tcodecid = esd->decoderConfig->objectTypeIndication;\n\t\t\t\tif (esd->URLString) hintType = 0;\n\t\t\t\t/*AAC*/\n\t\t\t\tif ((streamType==GF_STREAM_AUDIO)\n\t\t\t\t\t&& esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data\n\t\t\t\t /*(nb: we use mpeg4 for MPEG-2 AAC)*/\n\t\t\t\t && ((codecid==GF_CODECID_AAC_MPEG4) || (codecid==GF_CODECID_AAC_MPEG2_MP) || (codecid==GF_CODECID_AAC_MPEG2_LCP) || (codecid==GF_CODECID_AAC_MPEG2_SSRP)) ) {",
"\t\t\t\t\tu32 sample_rate;\n\t\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\t\tgf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tnb_ch = a_cfg.nb_chan;\n\t\t\t\t\tsample_rate = a_cfg.base_sr;\n\t\t\t\t\tPL_ID = a_cfg.audioPL;\n\t\t\t\t\tswitch (a_cfg.base_object_type) {\n\t\t\t\t\tcase GF_M4A_AAC_MAIN:\n\t\t\t\t\tcase GF_M4A_AAC_LC:\n\t\t\t\t\t\tif (flags & GP_RTP_PCK_USE_LATM_AAC) {\n\t\t\t\t\t\t\thintType = GF_RTP_PAYT_LATM;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tcase GF_M4A_AAC_SBR:\n\t\t\t\t\tcase GF_M4A_AAC_PS:\n\t\t\t\t\tcase GF_M4A_AAC_LTP:\n\t\t\t\t\tcase GF_M4A_AAC_SCALABLE:\n\t\t\t\t\tcase GF_M4A_ER_AAC_LC:\n\t\t\t\t\tcase GF_M4A_ER_AAC_LTP:\n\t\t\t\t\tcase GF_M4A_ER_AAC_SCALABLE:\n\t\t\t\t\t\tmpeg4mode = \"AAC\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase GF_M4A_CELP:\n\t\t\t\t\tcase GF_M4A_ER_CELP:\n\t\t\t\t\t\tmpeg4mode = \"CELP\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\trequired_rate = sample_rate;\n\t\t\t\t}\n\t\t\t\t/*MPEG1/2 audio*/\n\t\t\t\telse if ((streamType==GF_STREAM_AUDIO) && ((codecid==GF_CODECID_MPEG2_PART3) || (codecid==GF_CODECID_MPEG_AUDIO))) {\n\t\t\t\t\tGF_ISOSample *samp = NULL;\n\t\t\t\t\tif (!is_crypted)\n\t\t\t\t\t\t samp = gf_isom_get_sample(file, TrackNum, 1, NULL);",
"\t\t\t\t\tif (samp && (samp->dataLength>3)) {\n\t\t\t\t\t\tu32 hdr = GF_4CC((u32)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\tnb_ch = gf_mp3_num_channels(hdr);\n\t\t\t\t\t\thintType = GF_RTP_PAYT_MPEG12_AUDIO;\n\t\t\t\t\t\t/*use official RTP/AVP payload type*/\n\t\t\t\t\t\tOfficialPayloadID = 14;\n\t\t\t\t\t\trequired_rate = 90000;\n\t\t\t\t\t}\n\t\t\t\t\t/*encrypted MP3 must be sent through MPEG-4 generic to signal all ISMACryp stuff*/\n\t\t\t\t\telse {\n\t\t\t\t\t\tu32 sample_rate;\n\t\t\t\t\t\tgf_isom_get_audio_info(file, TrackNum, 1, &sample_rate, &nb_ch, NULL);\n\t\t\t\t\t\trequired_rate = sample_rate;\n\t\t\t\t\t}\n\t\t\t\t\tif (samp)\n\t\t\t\t\t\tgf_isom_sample_del(&samp);",
"\t\t\t\t}\n\t\t\t\t/*QCELP audio*/\n\t\t\t\telse if ((streamType==GF_STREAM_AUDIO) && (codecid==GF_CODECID_QCELP)) {\n\t\t\t\t\thintType = GF_RTP_PAYT_QCELP;\n\t\t\t\t\tOfficialPayloadID = 12;\n\t\t\t\t\trequired_rate = 8000;\n\t\t\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\t\t\tnb_ch = 1;\n\t\t\t\t}\n\t\t\t\t/*EVRC/SVM audio*/\n\t\t\t\telse if ((streamType==GF_STREAM_AUDIO) && ((codecid==GF_CODECID_EVRC) || (codecid==GF_CODECID_SMV)) ) {\n\t\t\t\t\thintType = GF_RTP_PAYT_EVRC_SMV;\n\t\t\t\t\trequired_rate = 8000;\n\t\t\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\t\t\tnb_ch = 1;\n\t\t\t\t}\n\t\t\t\t/*visual streams*/\n\t\t\t\telse if (streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif ((codecid==GF_CODECID_MPEG4_PART2) && esd->decoderConfig->decoderSpecificInfo) {\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\tPL_ID = dsi.VideoPL;\n\t\t\t\t\t}\n\t\t\t\t\t/*MPEG1/2 video*/\n\t\t\t\t\tif ( ((codecid>=GF_CODECID_MPEG2_SIMPLE) && (codecid<=GF_CODECID_MPEG2_422)) || (codecid==GF_CODECID_MPEG1)) {\n\t\t\t\t\t\tif (!is_crypted) {\n\t\t\t\t\t\t\thintType = GF_RTP_PAYT_MPEG12_VIDEO;\n\t\t\t\t\t\t\tOfficialPayloadID = 32;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*for ISMA*/\n\t\t\t\t\tif (is_crypted) {\n\t\t\t\t\t\t/*that's another pain with ISMACryp, even if no B-frames the DTS is signaled...*/\n\t\t\t\t\t\tif (codecid==GF_CODECID_MPEG4_PART2) force_dts_delta = 22;\n\t\t\t\t\t\telse if ((codecid==GF_CODECID_AVC) || (codecid==GF_CODECID_SVC)) {\n\t\t\t\t\t\t\tflags &= ~GP_RTP_PCK_USE_MULTI;\n\t\t\t\t\t\t\tforce_dts_delta = 22;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tflags |= GP_RTP_PCK_SIGNAL_RAP | GP_RTP_PCK_SIGNAL_TS;\n\t\t\t\t\t}",
"\t\t\t\t\trequired_rate = default_rtp_rate;\n\t\t\t\t}\n\t\t\t\t/*systems streams*/\n\t\t\t\telse if (gf_isom_has_sync_shadows(file, TrackNum) || gf_isom_has_sample_dependency(file, TrackNum)) {\n\t\t\t\t\tflags |= GP_RTP_PCK_SYSTEMS_CAROUSEL;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor*)esd);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_H263:\n\t\t\thintType = GF_RTP_PAYT_H263;\n\t\t\trequired_rate = 90000;\n\t\t\tstreamType = GF_STREAM_VISUAL;\n\t\t\tOfficialPayloadID = 34;\n\t\t\t/*not 100% compliant (short header is missing) but should still work*/\n\t\t\tcodecid = GF_CODECID_MPEG4_PART2;\n\t\t\tPL_ID = 0x01;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_AMR:\n\t\t\trequired_rate = 8000;\n\t\t\thintType = GF_RTP_PAYT_AMR;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\thas_mpeg4_mapping = 0;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_AMR_WB:\n\t\t\trequired_rate = 16000;\n\t\t\thintType = GF_RTP_PAYT_AMR_WB;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\thas_mpeg4_mapping = 0;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_AVC_H264:\n\t\tcase GF_ISOM_SUBTYPE_AVC2_H264:\n\t\tcase GF_ISOM_SUBTYPE_AVC3_H264:\n\t\tcase GF_ISOM_SUBTYPE_AVC4_H264:\n\t\tcase GF_ISOM_SUBTYPE_SVC_H264:\n\t\tcase GF_ISOM_SUBTYPE_MVC_H264:\n\t\t{\n\t\t\tGF_AVCConfig *avcc = gf_isom_avc_config_get(file, TrackNum, 1);\n\t\t\tGF_AVCConfig *svcc = gf_isom_svc_config_get(file, TrackNum, 1);\n\t\t\tGF_AVCConfig *mvcc = gf_isom_mvc_config_get(file, TrackNum, 1);",
"\t\t\tif (!avcc && !svcc && !mvcc) {\n\t\t\t\t*e = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\treturn NULL;\n\t\t\t}",
"\t\t\trequired_rate = 90000;\t/* \"90 kHz clock rate MUST be used\"*/\n\t\t\thintType = GF_RTP_PAYT_H264_AVC;\n\t\t\tif (TrackMediaSubType==GF_ISOM_SUBTYPE_SVC_H264)\n\t\t\t\thintType = GF_RTP_PAYT_H264_SVC;\n\t\t\telse if (TrackMediaSubType==GF_ISOM_SUBTYPE_MVC_H264)\n\t\t\t\thintType = GF_RTP_PAYT_H264_SVC;\n\t\t\tstreamType = GF_STREAM_VISUAL;\n\t\t\tavc_nalu_size = avcc ? avcc->nal_unit_size : svcc ? svcc->nal_unit_size : mvcc->nal_unit_size;\n\t\t\tcodecid = GF_CODECID_AVC;\n\t\t\tPL_ID = 0x0F;\n\t\t\tgf_odf_avc_cfg_del(avcc);\n\t\t\tgf_odf_avc_cfg_del(svcc);\n\t\t}\n\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_HVC1:\n\t\tcase GF_ISOM_SUBTYPE_HEV1:\n\t\tcase GF_ISOM_SUBTYPE_HVC2:\n\t\tcase GF_ISOM_SUBTYPE_HEV2:\n\t\t{\n\t\t\tGF_HEVCConfig *hevcc = gf_isom_hevc_config_get(file, TrackNum, 1);\n\t\t\tif (!hevcc) {\n\t\t\t\t*e = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\trequired_rate = 90000;\t/* \"90 kHz clock rate MUST be used\"*/\n\t\t\thintType = GF_RTP_PAYT_HEVC;\n\t\t\tstreamType = GF_STREAM_VISUAL;\n\t\t\tavc_nalu_size = hevcc->nal_unit_size;\n\t\t\tcodecid = GF_CODECID_HEVC;\n\t\t\tPL_ID = 0x0F;\n\t\t\tflags |= GP_RTP_PCK_USE_MULTI;\n\t\t\tgf_odf_hevc_cfg_del(hevcc);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_QCELP:\n\t\t\trequired_rate = 8000;\n\t\t\thintType = GF_RTP_PAYT_QCELP;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\tcodecid = GF_CODECID_QCELP;\n\t\t\tOfficialPayloadID = 12;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_EVRC:\n\t\tcase GF_ISOM_SUBTYPE_3GP_SMV:\n\t\t\trequired_rate = 8000;\n\t\t\thintType = GF_RTP_PAYT_EVRC_SMV;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\tcodecid = (TrackMediaSubType==GF_ISOM_SUBTYPE_3GP_EVRC) ? GF_CODECID_EVRC : GF_CODECID_SMV;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_DIMS:\n#if GPAC_ENABLE_3GPP_DIMS_RTP\n\t\t\thintType = GF_RTP_PAYT_3GPP_DIMS;\n\t\t\tstreamType = GF_STREAM_SCENE;\n#else\n\t\t\thintType = 0;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[RTP Packetizer] 3GPP DIMS over RTP disabled in build\\n\", streamType));\n#endif\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_AC3:\n\t\t\thintType = GF_RTP_PAYT_AC3;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\tgf_isom_get_audio_info(file, TrackNum, 1, NULL, &nb_ch, NULL);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_MP3:\n\t\t{\n\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, TrackNum, 1, NULL);\n\t\t\tif (samp && (samp->dataLength>3)) {\n\t\t\t\tu32 hdr = GF_4CC((u32)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\tnb_ch = gf_mp3_num_channels(hdr);\n\t\t\t} else {\n\t\t\t\tu32 bps;\n\t\t\t\tgf_isom_get_audio_info(file, TrackNum, 1, &required_rate, &nb_ch, &bps);\n\t\t\t}\n\t\t\thintType = GF_RTP_PAYT_MPEG12_AUDIO;\n\t\t\t/*use official RTP/AVP payload type*/\n\t\t\tOfficialPayloadID = 14;\n\t\t\trequired_rate = 90000;",
"\t\t\tif (samp)\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\t/*ERROR*/\n\t\t\thintType = 0;\n\t\t\tbreak;\n\t\t}\n\t}",
"\t/*not hintable*/\n\tif (!hintType) return NULL;\n\t/*we only support self-contained files for hinting*/\n\tgf_isom_get_data_reference(file, TrackNum, 1, &url, &urn);\n\tif (url || urn) return NULL;",
"\t*e = GF_OUT_OF_MEM;\n\tGF_SAFEALLOC(tmp, GF_RTPHinter);\n\tif (!tmp) return NULL;",
"\t/*override hinter type if requested and possible*/\n\tif (has_mpeg4_mapping && (flags & GP_RTP_PCK_FORCE_MPEG4)) {\n\t\thintType = GF_RTP_PAYT_MPEG4;\n\t\tavc_nalu_size = 0;\n\t}\n\t/*use static payload ID if enabled*/\n\telse if (OfficialPayloadID && (flags & GP_RTP_PCK_USE_STATIC_ID) ) {\n\t\tPayloadID = OfficialPayloadID;\n\t}",
"\ttmp->file = file;\n\ttmp->TrackNum = TrackNum;\n\ttmp->avc_nalu_size = avc_nalu_size;\n\ttmp->nb_chan = nb_ch;",
"\t/*spatial scalability check*/\n\ttmp->has_ctts = gf_isom_has_time_offset(file, TrackNum);",
"\t/*get sample info*/\n\tgf_media_get_sample_average_infos(file, TrackNum, &MinSize, &MaxSize, &avgTS, &maxDTSDelta, &const_dur, &bandwidth);",
"\t/*systems carousel: we need at least IDX and RAP signaling*/\n\tif (flags & GP_RTP_PCK_SYSTEMS_CAROUSEL) {\n\t\tflags |= GP_RTP_PCK_SIGNAL_RAP;\n\t}",
"\t/*update flags in MultiSL*/\n\tif (flags & GP_RTP_PCK_USE_MULTI) {\n\t\tif (MinSize != MaxSize) flags |= GP_RTP_PCK_SIGNAL_SIZE;\n\t\tif (!const_dur) flags |= GP_RTP_PCK_SIGNAL_TS;\n\t}\n\tif (tmp->has_ctts) flags |= GP_RTP_PCK_SIGNAL_TS;",
"\t/*default SL for RTP */\n\tInitSL_RTP(&my_sl);",
"\tmy_sl.timestampResolution = gf_isom_get_media_timescale(file, TrackNum);\n\t/*override clockrate if set*/\n\tif (required_rate) {\n\t\tDouble sc = required_rate;\n\t\tsc /= my_sl.timestampResolution;\n\t\tmaxDTSDelta = (u32) (maxDTSDelta*sc);\n\t\tmy_sl.timestampResolution = required_rate;\n\t}\n\t/*switch to RTP TS*/\n\tmax_ptime = (u32) (max_ptime * my_sl.timestampResolution / 1000);",
"\tmy_sl.AUSeqNumLength = gf_get_bit_size(gf_isom_get_sample_count(file, TrackNum));\n\tif (my_sl.AUSeqNumLength>16) my_sl.AUSeqNumLength=16;",
"\tmy_sl.CUDuration = const_dur;",
"\tif (gf_isom_has_sync_points(file, TrackNum)) {\n\t\tmy_sl.useRandomAccessPointFlag = 1;\n\t} else {\n\t\tmy_sl.useRandomAccessPointFlag = 0;\n\t\tmy_sl.hasRandomAccessUnitsOnlyFlag = 1;\n\t}",
"\tif (is_crypted) {\n\t\tBool use_sel_enc;\n\t\tgf_isom_get_ismacryp_info(file, TrackNum, 1, NULL, NULL, NULL, NULL, NULL, &use_sel_enc, &IV_length, &KI_length);\n\t\tif (use_sel_enc) flags |= GP_RTP_PCK_SELECTIVE_ENCRYPTION;\n\t}",
"\t// in case a different timescale was provided\n\ttmp->OrigTimeScale = gf_isom_get_media_timescale(file, TrackNum);\n\ttmp->rtp_p = gf_rtp_builder_new(hintType, &my_sl, flags, tmp,\n\t MP4T_OnNewPacket, MP4T_OnPacketDone,\n\t /*if copy, no data ref*/\n\t copy_media ? NULL : MP4T_OnDataRef,\n\t MP4T_OnData);",
"\t//init the builder\n\tgf_rtp_builder_init(tmp->rtp_p, PayloadID, Path_MTU, max_ptime,\n\t streamType, codecid, PL_ID, MinSize, MaxSize, avgTS, maxDTSDelta, IV_length, KI_length, mpeg4mode);",
"\t/*ISMA compliance is a pain...*/\n\tif (force_dts_delta) tmp->rtp_p->slMap.DTSDeltaLength = force_dts_delta;",
"\n\t/*\t\tHint Track Setup\t*/\n\ttmp->TrackID = gf_isom_get_track_id(file, TrackNum);\n\ttmp->HintID = tmp->TrackID + 65535;\n\twhile (gf_isom_get_track_by_id(file, tmp->HintID)) tmp->HintID++;",
"\ttmp->HintTrack = gf_isom_new_track(file, tmp->HintID, GF_ISOM_MEDIA_HINT, my_sl.timestampResolution);\n\tgf_isom_setup_hint_track(file, tmp->HintTrack, GF_ISOM_HINT_RTP);\n\t/*create a hint description*/\n\tgf_isom_new_hint_description(file, tmp->HintTrack, -1, -1, 0, &descIndex);\n\tgf_isom_rtp_set_timescale(file, tmp->HintTrack, descIndex, my_sl.timestampResolution);",
"\tif (hintType==GF_RTP_PAYT_MPEG4) {\n\t\ttmp->rtp_p->slMap.CodecID = codecid;\n\t\t/*set this SL for extraction.*/\n\t\tgf_isom_set_extraction_slc(file, TrackNum, 1, &my_sl);\n\t}\n\ttmp->bandwidth = bandwidth;",
"\t/*set interleaving*/\n\tgf_isom_set_track_interleaving_group(file, TrackNum, InterleaveGroupID);\n\tif (!copy_media) {\n\t\t/*if we don't copy data set hint track and media track in the same group*/\n\t\tgf_isom_set_track_interleaving_group(file, tmp->HintTrack, InterleaveGroupID);\n\t} else {\n\t\tgf_isom_set_track_interleaving_group(file, tmp->HintTrack, InterleaveGroupID + OFFSET_HINT_GROUP_ID);\n\t}\n\t/*use user-secified priority*/\n\tInterleaveGroupPriority*=2;\n\tgf_isom_set_track_priority_in_group(file, TrackNum, InterleaveGroupPriority+1);\n\tgf_isom_set_track_priority_in_group(file, tmp->HintTrack, InterleaveGroupPriority);",
"#if 0\n#endif\n\t*e = GF_OK;\n\treturn tmp;\n}",
"GF_EXPORT\nGF_Err gf_hinter_track_force_no_offsets(GF_RTPHinter *tkHinter)\n{\n\tGF_Err e;\n\tif (!tkHinter) return GF_BAD_PARAM;\n\te = gf_isom_rtp_set_time_offset(tkHinter->file, tkHinter->HintTrack, 1, 0);\n\tif (e) return e;\n\treturn gf_isom_rtp_set_time_sequence_offset(tkHinter->file, tkHinter->HintTrack, 1, 0);\n}",
"GF_EXPORT\nu32 gf_hinter_track_get_bandwidth(GF_RTPHinter *tkHinter)\n{\n\treturn tkHinter->bandwidth;\n}",
"GF_EXPORT\nu32 gf_hinter_track_get_flags(GF_RTPHinter *tkHinter)\n{\n\treturn tkHinter->rtp_p->flags;\n}\nGF_EXPORT\nvoid gf_hinter_track_get_payload_name(GF_RTPHinter *tkHinter, char *payloadName)\n{\n\tchar mediaName[30];\n\tgf_rtp_builder_get_payload_name(tkHinter->rtp_p, payloadName, mediaName);\n}",
"GF_EXPORT\nvoid gf_hinter_track_del(GF_RTPHinter *tkHinter)\n{\n\tif (!tkHinter) return;",
"\tif (tkHinter->rtp_p) gf_rtp_builder_del(tkHinter->rtp_p);\n\tgf_free(tkHinter);\n}",
"GF_EXPORT\nGF_Err gf_hinter_track_process(GF_RTPHinter *tkHint)\n{\n\tGF_Err e;\n\tu32 i, descIndex, duration;\n\tu64 ts;\n\tu8 PadBits;\n\tGF_Fraction ft;\n\tGF_ISOSample *samp;",
"\ttkHint->HintSample = tkHint->RTPTime = 0;",
"\ttkHint->TotalSample = gf_isom_get_sample_count(tkHint->file, tkHint->TrackNum);\n\tft.num = tkHint->rtp_p->sl_config.timestampResolution;\n\tft.den = tkHint->OrigTimeScale;",
"\te = GF_OK;\n\tfor (i=0; i<tkHint->TotalSample; i++) {\n\t\tsamp = gf_isom_get_sample(tkHint->file, tkHint->TrackNum, i+1, &descIndex);\n\t\tif (!samp) return gf_isom_last_error(tkHint->file);",
"\t\t//setup SL\n\t\ttkHint->CurrentSample = i + 1;",
"\t\t/*keep same AU indicator if sync shadow - TODO FIXME: this assumes shadows are placed interleaved with\n\t\tthe track content which is the case for GPAC scene carousel generation, but may not always be true*/\n\t\tif (samp->IsRAP==RAP_REDUNDANT) {\n\t\t\ttkHint->rtp_p->sl_header.AU_sequenceNumber -= 1;\n\t\t\tsamp->IsRAP = RAP;\n\t\t}",
"\t\tts = ft.num * (samp->DTS+samp->CTS_Offset) / ft.den;\n\t\ttkHint->rtp_p->sl_header.compositionTimeStamp = ts;",
"\t\tts = ft.num * samp->DTS / ft.den;\n\t\ttkHint->rtp_p->sl_header.decodingTimeStamp = ts;\n\t\ttkHint->rtp_p->sl_header.randomAccessPointFlag = samp->IsRAP;",
"\t\ttkHint->base_offset_in_sample = 0;\n\t\t/*crypted*/\n\t\tif (tkHint->rtp_p->slMap.IV_length) {\n\t\t\tGF_ISMASample *s = gf_isom_get_ismacryp_sample(tkHint->file, tkHint->TrackNum, samp, descIndex);\n\t\t\t/*one byte take for selective_enc flag*/\n\t\t\tif (s->flags & GF_ISOM_ISMA_USE_SEL_ENC) tkHint->base_offset_in_sample += 1;\n\t\t\tif (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) tkHint->base_offset_in_sample += s->IV_length + s->KI_length;\n\t\t\tgf_free(samp->data);\n\t\t\tsamp->data = s->data;\n\t\t\tsamp->dataLength = s->dataLength;\n\t\t\tgf_rtp_builder_set_cryp_info(tkHint->rtp_p, s->IV, (char*)s->key_indicator, (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) ? 1 : 0);\n\t\t\ts->data = NULL;\n\t\t\ts->dataLength = 0;\n\t\t\tgf_isom_ismacryp_delete_sample(s);\n\t\t}",
"\t\tif (tkHint->rtp_p->sl_config.usePaddingFlag) {\n\t\t\tgf_isom_get_sample_padding_bits(tkHint->file, tkHint->TrackNum, i+1, &PadBits);\n\t\t\ttkHint->rtp_p->sl_header.paddingBits = PadBits;\n\t\t} else {\n\t\t\ttkHint->rtp_p->sl_header.paddingBits = 0;\n\t\t}",
"\t\tduration = gf_isom_get_sample_duration(tkHint->file, tkHint->TrackNum, i+1);\n//\t\tts = (u32) (ft * (s64) (duration));",
"\t\t/*unpack nal units*/\n\t\tif (tkHint->avc_nalu_size) {\n\t\t\tu32 v, size;\n\t\t\tu32 remain = samp->dataLength;\n\t\t\tchar *ptr = samp->data;",
"\t\t\ttkHint->rtp_p->sl_header.accessUnitStartFlag = 1;\n\t\t\ttkHint->rtp_p->sl_header.accessUnitEndFlag = 0;\n\t\t\twhile (remain) {\n\t\t\t\tsize = 0;\n\t\t\t\tv = tkHint->avc_nalu_size;\n\t\t\t\tif (v>remain) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size length is %d but only %d bytes left in sample %d\\n\", v, remain, tkHint->CurrentSample));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\twhile (v) {\n\t\t\t\t\tsize |= (u8) *ptr;\n\t\t\t\t\tptr++;\n\t\t\t\t\tremain--;\n\t\t\t\t\tv-=1;\n\t\t\t\t\tif (v) size<<=8;\n\t\t\t\t}\n\t\t\t\ttkHint->base_offset_in_sample = samp->dataLength-remain;\n\t\t\t\tif (remain < size) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size is %d but only %d bytes left in sample %d\\n\", size, remain, tkHint->CurrentSample));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tremain -= size;\n\t\t\t\ttkHint->rtp_p->sl_header.accessUnitEndFlag = remain ? 0 : 1;",
"\t\t\t\te = gf_rtp_builder_process(tkHint->rtp_p, ptr, size, (u8) !remain, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) );\n\t\t\t\tptr += size;",
"\t\t\t\ttkHint->rtp_p->sl_header.accessUnitStartFlag = 0;\n\t\t\t}\n\t\t} else {\n\t\t\te = gf_rtp_builder_process(tkHint->rtp_p, samp->data, samp->dataLength, 1, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) );\n\t\t}\n\t\ttkHint->rtp_p->sl_header.packetSequenceNumber += 1;",
"\t\t//signal some progress\n\t\tgf_set_progress(\"Hinting\", tkHint->CurrentSample, tkHint->TotalSample);",
"\t\ttkHint->rtp_p->sl_header.AU_sequenceNumber += 1;\n\t\tgf_isom_sample_del(&samp);",
"\t\tif (e) return e;\n\t}",
"\t//flush\n\tgf_rtp_builder_process(tkHint->rtp_p, NULL, 0, 1, 0, 0, 0);",
"\tgf_isom_end_hint_sample(tkHint->file, tkHint->HintTrack, (u8) tkHint->SampleIsRAP);\n\treturn GF_OK;\n}",
"static u32 write_nalu_config_array(char *sdpLine, GF_List *nalus)\n{\n\tu32 i, count, b64s;\n\tchar b64[200];",
"\tcount = gf_list_count(nalus);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = (GF_NALUFFParam *)gf_list_get(nalus, i);\n\t\tb64s = gf_base64_encode(sl->data, sl->size, b64, 200);\n\t\tb64[b64s]=0;\n\t\tstrcat(sdpLine, b64);\n\t\tif (i+1<count) strcat(sdpLine, \",\");\n\t}\n\treturn count;\n}",
"static void write_avc_config(char *sdpLine, GF_AVCConfig *avcc, GF_AVCConfig *svcc)\n{\n\tu32 count = 0;",
"\tif (avcc) count += gf_list_count(avcc->sequenceParameterSets) + gf_list_count(avcc->pictureParameterSets) + gf_list_count(avcc->sequenceParameterSetExtensions);\n\tif (svcc) count += gf_list_count(svcc->sequenceParameterSets) + gf_list_count(svcc->pictureParameterSets);\n\tif (!count) return;",
"\tstrcat(sdpLine, \"; sprop-parameter-sets=\");",
"\tif (avcc) {\n\t\tcount = write_nalu_config_array(sdpLine, avcc->sequenceParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t\tcount = write_nalu_config_array(sdpLine, avcc->sequenceParameterSetExtensions);\n\t\tif (count) strcat(sdpLine, \",\");\n\t\tcount = write_nalu_config_array(sdpLine, avcc->pictureParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t}",
"\tif (svcc) {\n\t\tcount = write_nalu_config_array(sdpLine, svcc->sequenceParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t\tcount = write_nalu_config_array(sdpLine, svcc->pictureParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t}\n\tcount = (u32) strlen(sdpLine);\n\tif (sdpLine[count-1] == ',')\n\t\tsdpLine[count-1] = 0;\n}",
"GF_EXPORT\nGF_Err gf_hinter_track_finalize(GF_RTPHinter *tkHint, Bool AddSystemInfo)\n{\n\tu32 Width, Height;\n\tGF_ESD *esd;\n\tchar sdpLine[20000];\n\tchar mediaName[30], payloadName[30];\n u32 mtype;",
"\tWidth = Height = 0;\n\tgf_isom_sdp_clean_track(tkHint->file, tkHint->TrackNum);\n mtype = gf_isom_get_media_type(tkHint->file, tkHint->TrackNum);\n if (gf_isom_is_video_handler_type(mtype))\n\t\tgf_isom_get_visual_info(tkHint->file, tkHint->TrackNum, 1, &Width, &Height);",
"\tgf_rtp_builder_get_payload_name(tkHint->rtp_p, payloadName, mediaName);",
"\t/*TODO- extract out of rtp_p for future live tools*/\n\tsprintf(sdpLine, \"m=%s 0 RTP/%s %d\", mediaName, tkHint->rtp_p->slMap.IV_length ? \"SAVP\" : \"AVP\", tkHint->rtp_p->PayloadType);\n\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\tif (tkHint->bandwidth) {\n\t\tsprintf(sdpLine, \"b=AS:%d\", tkHint->bandwidth);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\tif (tkHint->nb_chan) {\n\t\tsprintf(sdpLine, \"a=rtpmap:%d %s/%d/%d\", tkHint->rtp_p->PayloadType, payloadName, tkHint->rtp_p->sl_config.timestampResolution, tkHint->nb_chan);\n\t} else {\n\t\tsprintf(sdpLine, \"a=rtpmap:%d %s/%d\", tkHint->rtp_p->PayloadType, payloadName, tkHint->rtp_p->sl_config.timestampResolution);\n\t}\n\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t/*control for MPEG-4*/\n\tif (AddSystemInfo) {\n\t\tsprintf(sdpLine, \"a=mpeg4-esid:%d\", gf_isom_get_track_id(tkHint->file, tkHint->TrackNum));\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*control for QTSS/DSS*/\n\tsprintf(sdpLine, \"a=control:trackID=%d\", gf_isom_get_track_id(tkHint->file, tkHint->HintTrack));\n\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);",
"\t/*H263 extensions*/\n\tif (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H263) {\n\t\tsprintf(sdpLine, \"a=cliprect:0,0,%d,%d\", Height, Width);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*AMR*/\n\telse if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_AMR) || (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_AMR_WB)) {\n\t\tsprintf(sdpLine, \"a=fmtp:%d octet-align=1\", tkHint->rtp_p->PayloadType);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*Text*/\n\telse if (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_3GPP_TEXT) {\n\t\tu32 w, h, i, m_w, m_h;\n\t\ts32 tx, ty;\n\t\ts16 l;",
"\t\tgf_isom_get_track_layout_info(tkHint->file, tkHint->TrackNum, &w, &h, &tx, &ty, &l);\n\t\tm_w = w;\n\t\tm_h = h;\n\t\tfor (i=0; i<gf_isom_get_track_count(tkHint->file); i++) {\n\t\t\tswitch (gf_isom_get_media_type(tkHint->file, i+1)) {\n\t\t\tcase GF_ISOM_MEDIA_SCENE:\n\t\t\tcase GF_ISOM_MEDIA_VISUAL:\n\t\t\tcase GF_ISOM_MEDIA_AUXV:\n\t\t\tcase GF_ISOM_MEDIA_PICT:\n\t\t\t\tgf_isom_get_track_layout_info(tkHint->file, i+1, &w, &h, &tx, &ty, &l);\n\t\t\t\tif (w>m_w) m_w = w;\n\t\t\t\tif (h>m_h) m_h = h;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}",
"\t\tgf_media_format_ttxt_sdp(tkHint->rtp_p, payloadName, sdpLine, w, h, tx, ty, l, m_w, m_h, NULL);",
"\t\tstrcat(sdpLine, \"; tx3g=\");\n\t\tfor (i=0; i<gf_isom_get_sample_description_count(tkHint->file, tkHint->TrackNum); i++) {\n\t\t\tu8 *tx3g;\n\t\t\tchar buffer[2000];\n\t\t\tu32 tx3g_len, len;\n\t\t\tgf_isom_text_get_encoded_tx3g(tkHint->file, tkHint->TrackNum, i+1, GF_RTP_TX3G_SIDX_OFFSET, &tx3g, &tx3g_len);\n\t\t\tlen = gf_base64_encode(tx3g, tx3g_len, buffer, 2000);\n\t\t\tgf_free(tx3g);\n\t\t\tbuffer[len] = 0;\n\t\t\tif (i) strcat(sdpLine, \", \");\n\t\t\tstrcat(sdpLine, buffer);\n\t\t}\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*EVRC/SMV in non header-free mode*/\n\telse if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_EVRC_SMV) && (tkHint->rtp_p->auh_size>1)) {\n\t\tsprintf(sdpLine, \"a=fmtp:%d maxptime=%d\", tkHint->rtp_p->PayloadType, tkHint->rtp_p->auh_size*20);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*H264/AVC*/\n\telse if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H264_AVC) || (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H264_SVC)) {\n\t\tGF_AVCConfig *avcc = gf_isom_avc_config_get(tkHint->file, tkHint->TrackNum, 1);\n\t\tGF_AVCConfig *svcc = gf_isom_svc_config_get(tkHint->file, tkHint->TrackNum, 1);\n\t\t/*TODO - check syntax for SVC (might be some extra signaling)*/",
"\t\tif (avcc) {\n\t\t\tsprintf(sdpLine, \"a=fmtp:%d profile-level-id=%02X%02X%02X; packetization-mode=1\", tkHint->rtp_p->PayloadType, avcc->AVCProfileIndication, avcc->profile_compatibility, avcc->AVCLevelIndication);\n\t\t} else {\n\t\t\tif (!svcc)\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\tsprintf(sdpLine, \"a=fmtp:%d profile-level-id=%02X%02X%02X; packetization-mode=1\", tkHint->rtp_p->PayloadType, svcc->AVCProfileIndication, svcc->profile_compatibility, svcc->AVCLevelIndication);\n\t\t}",
"\t\twrite_avc_config(sdpLine, avcc, svcc);",
"\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t\tgf_odf_avc_cfg_del(avcc);\n\t\tgf_odf_avc_cfg_del(svcc);\n\t}\n\t/*MPEG-4 decoder config*/\n\telse if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_MPEG4) {\n\t\tesd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1);",
"\t\tif (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) {\n\t\t\tgf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength);\n\t\t} else {\n\t\t\tgf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, NULL, 0);\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);",
"\t\tif (tkHint->rtp_p->slMap.IV_length) {\n\t\t\tconst char *kms;\n\t\t\tgf_isom_get_ismacryp_info(tkHint->file, tkHint->TrackNum, 1, NULL, NULL, NULL, NULL, &kms, NULL, NULL, NULL);\n\t\t\tif (!strnicmp(kms, \"(key)\", 5) || !strnicmp(kms, \"(ipmp)\", 6) || !strnicmp(kms, \"(uri)\", 5)) {\n\t\t\t\tstrcat(sdpLine, \"; ISMACrypKey=\");\n\t\t\t} else {\n\t\t\t\tstrcat(sdpLine, \"; ISMACrypKey=(uri)\");\n\t\t\t}\n\t\t\tstrcat(sdpLine, kms);\n\t\t}",
"\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*MPEG-4 Audio LATM*/\n\telse if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_LATM) {\n\t\tGF_BitStream *bs;\n\t\tu8 *config_bytes;\n\t\tu32 config_size;",
"\t\t/* form config string */\n\t\tbs = gf_bs_new(NULL, 32, GF_BITSTREAM_WRITE);\n\t\tgf_bs_write_int(bs, 0, 1); /* AudioMuxVersion */\n\t\tgf_bs_write_int(bs, 1, 1); /* all streams same time */\n\t\tgf_bs_write_int(bs, 0, 6); /* numSubFrames */\n\t\tgf_bs_write_int(bs, 0, 4); /* numPrograms */\n\t\tgf_bs_write_int(bs, 0, 3); /* numLayer */",
"\t\t/* audio-specific config */\n\t\tesd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1);\n\t\tif (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo) {\n\t\t\t/*PacketVideo patch: don't signal SBR and PS stuff, not allowed in LATM with audioMuxVersion=0*/\n\t\t\tgf_bs_write_data(bs, esd->decoderConfig->decoderSpecificInfo->data, MIN(esd->decoderConfig->decoderSpecificInfo->dataLength, 2) );\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);",
"\t\t/* other data */\n\t\tgf_bs_write_int(bs, 0, 3); /* frameLengthType */\n\t\tgf_bs_write_int(bs, 0xff, 8); /* latmBufferFullness */\n\t\tgf_bs_write_int(bs, 0, 1); /* otherDataPresent */\n\t\tgf_bs_write_int(bs, 0, 1); /* crcCheckPresent */\n\t\tgf_bs_get_content(bs, &config_bytes, &config_size);\n\t\tgf_bs_del(bs);",
"\t\tgf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, config_bytes, config_size);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t\tgf_free(config_bytes);\n\t}\n#if GPAC_ENABLE_3GPP_DIMS_RTP\n\t/*3GPP DIMS*/\n\telse if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_3GPP_DIMS) {\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(tkHint->file, tkHint->TrackNum, 1, &Width, &Height);",
"\t\tgf_isom_get_dims_description(tkHint->file, tkHint->TrackNum, 1, &dims);\n\t\tsprintf(sdpLine, \"a=fmtp:%d Version-profile=%d\", tkHint->rtp_p->PayloadType, dims.profile);\n\t\tif (! dims.fullRequestHost) {\n\t\t\tchar fmt[200];\n\t\t\tstrcat(sdpLine, \";useFullRequestHost=0\");\n\t\t\tsprintf(fmt, \";pathComponents=%d\", dims.pathComponents);\n\t\t\tstrcat(sdpLine, fmt);\n\t\t}\n\t\tif (!dims.streamType) strcat(sdpLine, \";stream-type=secondary\");\n\t\tif (dims.containsRedundant == 1) strcat(sdpLine, \";contains-redundant=main\");\n\t\telse if (dims.containsRedundant == 2) strcat(sdpLine, \";contains-redundant=redundant\");",
"\t\tif (dims.textEncoding && strlen(dims.textEncoding)) {\n\t\t\tstrcat(sdpLine, \";text-encoding=\");\n\t\t\tstrcat(sdpLine, dims.textEncoding);\n\t\t}\n\t\tif (dims.contentEncoding && strlen(dims.contentEncoding)) {\n\t\t\tstrcat(sdpLine, \";content-coding=\");\n\t\t\tstrcat(sdpLine, dims.contentEncoding);\n\t\t}\n\t\tif (dims.contentEncoding && dims.content_script_types && strlen(dims.content_script_types) ) {\n\t\t\tstrcat(sdpLine, \";content-script-types=\");\n\t\t\tstrcat(sdpLine, dims.contentEncoding);\n\t\t}\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n#endif\n\t/*extensions for some mobile phones*/\n\tif (Width && Height) {\n\t\tsprintf(sdpLine, \"a=framesize:%d %d-%d\", tkHint->rtp_p->PayloadType, Width, Height);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}",
"\tesd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1);\n\tif (esd && esd->decoderConfig && (esd->decoderConfig->rvc_config || esd->decoderConfig->predefined_rvc_config)) {\n\t\tif (esd->decoderConfig->predefined_rvc_config) {\n\t\t\tsprintf(sdpLine, \"a=rvc-config-predef:%d\", esd->decoderConfig->predefined_rvc_config);\n\t\t} else {\n\t\t\t/*temporary ...*/\n\t\t\tif ((esd->decoderConfig->objectTypeIndication==GF_CODECID_AVC) || (esd->decoderConfig->objectTypeIndication==GF_CODECID_SVC)) {\n\t\t\t\tsprintf(sdpLine, \"a=rvc-config:%s\", \"http://download.tsi.telecom-paristech.fr/gpac/RVC/rvc_config_avc.xml\");\n\t\t\t} else {\n\t\t\t\tsprintf(sdpLine, \"a=rvc-config:%s\", \"http://download.tsi.telecom-paristech.fr/gpac/RVC/rvc_config_sp.xml\");\n\t\t\t}\n\t\t}\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);",
"\tgf_isom_set_track_enabled(tkHint->file, tkHint->HintTrack, GF_TRUE);\n\treturn GF_OK;\n}",
"GF_EXPORT\nBool gf_hinter_can_embbed_data(u8 *data, u32 data_size, u32 streamType)\n{\n\tchar data64[5000];\n\tu32 size64;",
"\tsize64 = gf_base64_encode(data, data_size, data64, 5000);\n\tif (!size64) return 0;\n\tswitch (streamType) {\n\tcase GF_STREAM_OD:\n\t\tsize64 += (u32) strlen(\"data:application/mpeg4-od-au;base64,\");\n\t\tbreak;\n\tcase GF_STREAM_SCENE:\n\t\tsize64 += (u32) strlen(\"data:application/mpeg4-bifs-au;base64,\");\n\t\tbreak;\n\tdefault:\n\t\t/*NOT NORMATIVE*/\n\t\tsize64 += (u32) strlen(\"data:application/mpeg4-es-au;base64,\");\n\t\tbreak;\n\t}\n\tif (size64>=255) return 0;\n\treturn 1;\n}",
"\nGF_EXPORT\nGF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];",
"\n\tgf_isom_sdp_clean(file);",
"\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);",
"\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;",
"\todT = sceneT = 0;\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (!gf_isom_is_track_in_root_od(file, i+1)) continue;\n\t\tswitch (gf_isom_get_media_type(file,i+1)) {\n\t\tcase GF_ISOM_MEDIA_OD:\n\t\t\todT = i+1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_MEDIA_SCENE:\n\t\t\tsceneT = i+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tremove_ocr = 0;\n\tif (IOD_Profile == GF_SDP_IOD_ISMA_STRICT) {\n\t\tIOD_Profile = GF_SDP_IOD_ISMA;\n\t\tremove_ocr = 1;\n\t}",
"\t/*if we want ISMA like iods, we need at least BIFS */\n\tif ( (IOD_Profile == GF_SDP_IOD_ISMA) && !sceneT ) return GF_BAD_PARAM;",
"\t/*do NOT change PLs, we assume they are correct*/\n\tiod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file);\n\tif (!iod) return GF_NOT_SUPPORTED;",
"\t/*rewrite an IOD with good SL config - embbed data if possible*/\n\tif (IOD_Profile == GF_SDP_IOD_ISMA) {\n\t\tGF_ESD *esd;\n\t\tBool is_ok = 1;\n\t\twhile (gf_list_count(iod->ESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}",
"\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);",
"\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);",
"\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;",
"\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}",
"\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {",
"\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);",
"\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;",
"\t\tgf_list_add(iod->ESDescriptors, esd);",
"\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\t\t\tesd = gf_isom_get_esd(file, i+1, 1);\n\t\t\t\tif (!esd) continue;\n\t\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}",
"\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);",
"\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);",
"\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);",
"\treturn GF_OK;\n}",
"\n#endif /*GPAC_DISABLE_ISOM_HINTING*/",
"#endif /*GPAC_DISABLE_ISOM*/"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [798], "buggy_code_start_loc": [796], "filenames": ["src/media_tools/isom_hinter.c"], "fixing_code_end_loc": [802], "fixing_code_start_loc": [796], "message": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is heap-based buffer overflow in the function gp_rtp_builder_do_avc() in ietf/rtp_pck_mpeg4.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:0.8.0:*:*:*:*:*:*:*", "matchCriteriaId": "93EEFCFD-7417-40E6-84BF-4EA630F2A8A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"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": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is heap-based buffer overflow in the function gp_rtp_builder_do_avc() in ietf/rtp_pck_mpeg4.c."}, {"lang": "es", "value": "Se detect\u00f3 un problema en GPAC versiones 0.8.0 y 1.0.1. Se presenta un desbordamiento del b\u00fafer en la regi\u00f3n heap de la memoria en la funci\u00f3n gp_rtp_builder_do_avc() en el archivo ietf/rtp_pck_mpeg4.c"}], "evaluatorComment": null, "id": "CVE-2020-35979", "lastModified": "2021-04-23T19:53:24.550", "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": null, "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": "2021-04-21T16:15:08.647", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/b15020f54aff24aaeb64b80771472be8e64a7adc"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1662"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/b15020f54aff24aaeb64b80771472be8e64a7adc"}, "type": "CWE-787"}
| 313
|
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-2012\n *\t\t\t\t\tAll rights reserved\n *\n * This file is part of GPAC / Media Tools sub-project\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/internal/media_dev.h>\n#include <gpac/base_coding.h>\n#include <gpac/mpeg4_odf.h>\n#include <gpac/constants.h>\n#include <gpac/maths.h>\n#include <gpac/internal/ietf_dev.h>",
"#ifndef GPAC_DISABLE_ISOM",
"void gf_media_get_sample_average_infos(GF_ISOFile *file, u32 Track, u32 *avgSize, u32 *MaxSize, u32 *TimeDelta, u32 *maxCTSDelta, u32 *const_duration, u32 *bandwidth)\n{\n\tu32 i, count, ts_diff;\n\tu64 prevTS, tdelta;\n\tDouble bw;\n\tGF_ISOSample *samp;",
"\t*avgSize = *MaxSize = 0;\n\t*TimeDelta = 0;\n\t*maxCTSDelta = 0;\n\tbw = 0;\n\tprevTS = 0;\n\ttdelta = 0;",
"\tcount = gf_isom_get_sample_count(file, Track);\n\tif (!count) return;\n\t*const_duration = 0;",
"\tfor (i=0; i<count; i++) {\n\t\tsamp = gf_isom_get_sample_info(file, Track, i+1, NULL, NULL);\n\t\tif (!samp) break;\n\t\t\n\t\t//get the size\n\t\t*avgSize += samp->dataLength;\n\t\tif (*MaxSize < samp->dataLength) *MaxSize = samp->dataLength;\n\t\tts_diff = (u32) (samp->DTS+samp->CTS_Offset - prevTS);\n\t\t//get the time\n\t\ttdelta += ts_diff;",
"\t\tif (i==1) {\n\t\t\t*const_duration = ts_diff;\n\t\t} else if ( (i<count-1) && (*const_duration != ts_diff) ) {\n\t\t\t*const_duration = 0;\n\t\t}",
"\t\tprevTS = samp->DTS+samp->CTS_Offset;\n\t\tbw += 8*samp->dataLength;",
"\t\t//get the CTS delta\n\t\tif ((samp->CTS_Offset>=0) && ((u32)samp->CTS_Offset > *maxCTSDelta))\n\t\t\t*maxCTSDelta = samp->CTS_Offset;\n\t\tgf_isom_sample_del(&samp);\n\t}\n\tif (count>1) *TimeDelta = (u32) (tdelta/ (count-1) );\n\telse *TimeDelta = (u32) tdelta;\n\t*avgSize /= count;\n\tbw *= gf_isom_get_media_timescale(file, Track);\n\tbw /= (s64) gf_isom_get_media_duration(file, Track);\n\tbw /= 1000;\n\t(*bandwidth) = (u32) (bw+0.5);",
"\t//delta is NOT an average, we need to know exactly how many bits are\n\t//needed to encode CTS-DTS for ANY samples\n}",
"\n#ifndef GPAC_DISABLE_ISOM_HINTING",
"/*RTP track hinter*/\nstruct __tag_isom_hinter\n{\n\tGF_ISOFile *file;\n\t/*IDs are kept for mp4 hint sample building*/\n\tu32 TrackNum, TrackID, HintTrack, HintID;\n\t/*current Hint sample and associated RTP time*/\n\tu32 HintSample, RTPTime;",
"\t/*track has composition time offset*/\n\tBool has_ctts;\n\t/*remember if first SL packet in RTP packet is RAP*/\n\tu8 SampleIsRAP;\n\tu32 base_offset_in_sample;\n\tu32 OrigTimeScale;\n\t/*rtp builder*/\n\tGP_RTPPacketizer *rtp_p;",
"\tu32 bandwidth, nb_chan;",
"\t/*NALU size for H264/AVC*/\n\tu32 avc_nalu_size;",
"\t/*stats*/\n\tu32 TotalSample, CurrentSample;\n};",
"\n/*\n\toffset for group ID for hint tracks in SimpleAV mode when all media data\n\tis copied to the hint track (no use interleaving hint and original in this case)\n\tthis offset is applied internally by the track hinter. Thus you shouldn't\n\tspecify a GroupID >= OFFSET_HINT_GROUP_ID if you want the lib to perform efficient\n\tinterleaving in any cases (referenced or copied media)\n*/\n#define OFFSET_HINT_GROUP_ID\t0x8000",
"void InitSL_RTP(GF_SLConfig *slc)\n{\n\tmemset(slc, 0, sizeof(GF_SLConfig));\n\tslc->tag = GF_ODF_SLC_TAG;\n\tslc->useTimestampsFlag = 1;\n\tslc->timestampLength = 32;\n}",
"void InitSL_NULL(GF_SLConfig *slc)\n{\n\tmemset(slc, 0, sizeof(GF_SLConfig));\n\tslc->tag = GF_ODF_SLC_TAG;\n\tslc->predefined = 0x01;\n}",
"",
"void MP4T_OnPacketDone(void *cbk, GF_RTPHeader *header)\n{\n\tu8 disposable;\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!tkHint || !tkHint->HintSample) return;\n\tassert(header->TimeStamp == tkHint->RTPTime);",
"\tdisposable = 0;\n\tif (tkHint->avc_nalu_size) {\n\t\tdisposable = tkHint->rtp_p->avc_non_idr ? 1 : 0;\n\t}\n\t/*for all other, assume that CTS=DTS means B-frame -> disposable*/\n\telse if (tkHint->has_ctts && (tkHint->rtp_p->sl_header.compositionTimeStamp==tkHint->rtp_p->sl_header.decodingTimeStamp)) {\n\t\tdisposable = 1;\n\t}",
"\tgf_isom_rtp_packet_set_flags(tkHint->file, tkHint->HintTrack, 0, 0, header->Marker, disposable, 0);\n}",
"\nvoid MP4T_OnDataRef(void *cbk, u32 payload_size, u32 offset_from_orig)\n{\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!tkHint || !payload_size) return;",
"\t/*add reference*/\n\tgf_isom_hint_sample_data(tkHint->file, tkHint->HintTrack, tkHint->TrackID,\n\t tkHint->CurrentSample, (u16) payload_size, offset_from_orig + tkHint->base_offset_in_sample,\n\t NULL, 0);\n}",
"void MP4T_OnData(void *cbk, u8 *data, u32 data_size, Bool is_header)\n{\n\tu8 at_begin;\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!data_size) return;",
"\tat_begin = is_header ? 1 : 0;\n\tif (data_size <= 14) {\n\t\tgf_isom_hint_direct_data(tkHint->file, tkHint->HintTrack, data, data_size, at_begin);\n\t} else {\n\t\tgf_isom_hint_sample_data(tkHint->file, tkHint->HintTrack, tkHint->HintID, 0, (u16) data_size, 0, data, at_begin);\n\t}\n}",
"\nvoid MP4T_OnNewPacket(void *cbk, GF_RTPHeader *header)\n{\n\ts32 res;\n\tGF_RTPHinter *tkHint = (GF_RTPHinter *)cbk;\n\tif (!tkHint) return;",
"\tres = (s32) (tkHint->rtp_p->sl_header.compositionTimeStamp - tkHint->rtp_p->sl_header.decodingTimeStamp);\n\tassert( !res || tkHint->has_ctts);\n\t/*do we need a new sample*/\n\tif (!tkHint->HintSample || (tkHint->RTPTime != header->TimeStamp)) {\n\t\t/*close current sample*/\n\t\tif (tkHint->HintSample) gf_isom_end_hint_sample(tkHint->file, tkHint->HintTrack, tkHint->SampleIsRAP);",
"\t\t/*start new sample: We use DTS as the sampling instant (RTP TS) to make sure\n\t\tall packets are sent in order*/\n\t\tgf_isom_begin_hint_sample(tkHint->file, tkHint->HintTrack, 1, header->TimeStamp-res);\n\t\ttkHint->HintSample ++;\n\t\ttkHint->RTPTime = header->TimeStamp;\n\t\ttkHint->SampleIsRAP = tkHint->rtp_p->sl_config.hasRandomAccessUnitsOnlyFlag ? 1 : tkHint->rtp_p->sl_header.randomAccessPointFlag;\n\t}\n\t/*create an RTP Packet with the appropriated marker flag - note: the flags are temp ones,\n\tthey are set when the full packet is signaled (to handle multi AUs per RTP)*/\n\tgf_isom_rtp_packet_begin(tkHint->file, tkHint->HintTrack, 0, 0, 0, header->Marker, header->PayloadType, 0, 0, header->SequenceNumber);\n\t/*Add the delta TS to make sure RTP TS is indeed the CTS (sampling time)*/\n\tif (res) gf_isom_rtp_packet_set_offset(tkHint->file, tkHint->HintTrack, res);\n}",
"\nGF_EXPORT\nGF_RTPHinter *gf_hinter_track_new(GF_ISOFile *file, u32 TrackNum,\n u32 Path_MTU, u32 max_ptime, u32 default_rtp_rate, u32 flags, u8 PayloadID,\n Bool copy_media, u32 InterleaveGroupID, u8 InterleaveGroupPriority, GF_Err *e)\n{",
"\tGF_SLConfig my_sl;\n\tu32 descIndex, MinSize, MaxSize, avgTS, streamType, codecid, const_dur, nb_ch, maxDTSDelta;\n\tu8 OfficialPayloadID;\n\tu32 TrackMediaSubType, TrackMediaType, hintType, nbEdts, required_rate, force_dts_delta, avc_nalu_size, PL_ID, bandwidth, IV_length, KI_length;\n\tconst char *url, *urn;\n\tchar *mpeg4mode;\n\tBool is_crypted, has_mpeg4_mapping;\n\tGF_RTPHinter *tmp;\n\tGF_ESD *esd;",
"\t*e = GF_BAD_PARAM;\n\tif (!file || !TrackNum || !gf_isom_get_track_id(file, TrackNum)) return NULL;",
"\tif (!gf_isom_get_sample_count(file, TrackNum)) {\n\t\t*e = GF_OK;\n\t\treturn NULL;\n\t}\n\t*e = GF_NOT_SUPPORTED;\n\tnbEdts = gf_isom_get_edits_count(file, TrackNum);\n\tif (nbEdts>1) {\n\t\tu64 et, sd, mt;\n\t\tGF_ISOEditType em;\n\t\tgf_isom_get_edit(file, TrackNum, 1, &et, &sd, &mt, &em);\n\t\tif ((nbEdts>2) || (em!=GF_ISOM_EDIT_EMPTY)) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Cannot hint track whith EditList\\n\"));\n\t\t\treturn NULL;\n\t\t}\n\t}\n\tif (nbEdts) gf_isom_remove_edits(file, TrackNum);",
"\tif (!gf_isom_is_track_enabled(file, TrackNum)) return NULL;",
"\t/*by default NO PL signaled*/\n\tPL_ID = 0;\n\tOfficialPayloadID = 0;\n\tforce_dts_delta = 0;\n\tstreamType = 0;\n\tmpeg4mode = NULL;\n\trequired_rate = 0;\n\tis_crypted = 0;\n\tIV_length = KI_length = 0;\n\tcodecid = 0;\n\tnb_ch = 0;\n\tavc_nalu_size = 0;\n\thas_mpeg4_mapping = 1;\n\tconst_dur = 0;\n\tbandwidth=0;\n\tTrackMediaType = gf_isom_get_media_type(file, TrackNum);",
"\t/*for max compatibility with QT*/\n\tif (!default_rtp_rate) default_rtp_rate = 90000;",
"\t/*timed-text is a bit special, we support multiple stream descriptions & co*/\n\tif ( (TrackMediaType==GF_ISOM_MEDIA_TEXT) || (TrackMediaType==GF_ISOM_MEDIA_SUBT)) {\n\t\thintType = GF_RTP_PAYT_3GPP_TEXT;\n\t\tcodecid = GF_CODECID_TEXT_MPEG4;\n\t\tstreamType = GF_STREAM_TEXT;\n\t\t/*fixme - this works cos there's only one PL for text in mpeg4 at the current time*/\n\t\tPL_ID = 0x10;\n\t} else {\n\t\tif (gf_isom_get_sample_description_count(file, TrackNum) > 1) return NULL;",
"\t\tTrackMediaSubType = gf_isom_get_media_subtype(file, TrackNum, 1);\n\t\tswitch (TrackMediaSubType) {\n\t\tcase GF_ISOM_SUBTYPE_MPEG4_CRYP:\n\t\t\tis_crypted = 1;\n\t\tcase GF_ISOM_SUBTYPE_MPEG4:\n\t\t\tesd = gf_isom_get_esd(file, TrackNum, 1);\n\t\t\thintType = GF_RTP_PAYT_MPEG4;\n\t\t\tif (esd && esd->decoderConfig) {\n\t\t\t\tstreamType = esd->decoderConfig->streamType;\n\t\t\t\tcodecid = esd->decoderConfig->objectTypeIndication;\n\t\t\t\tif (esd->URLString) hintType = 0;\n\t\t\t\t/*AAC*/\n\t\t\t\tif ((streamType==GF_STREAM_AUDIO)\n\t\t\t\t\t&& esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data\n\t\t\t\t /*(nb: we use mpeg4 for MPEG-2 AAC)*/\n\t\t\t\t && ((codecid==GF_CODECID_AAC_MPEG4) || (codecid==GF_CODECID_AAC_MPEG2_MP) || (codecid==GF_CODECID_AAC_MPEG2_LCP) || (codecid==GF_CODECID_AAC_MPEG2_SSRP)) ) {",
"\t\t\t\t\tu32 sample_rate;\n\t\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\t\tgf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tnb_ch = a_cfg.nb_chan;\n\t\t\t\t\tsample_rate = a_cfg.base_sr;\n\t\t\t\t\tPL_ID = a_cfg.audioPL;\n\t\t\t\t\tswitch (a_cfg.base_object_type) {\n\t\t\t\t\tcase GF_M4A_AAC_MAIN:\n\t\t\t\t\tcase GF_M4A_AAC_LC:\n\t\t\t\t\t\tif (flags & GP_RTP_PCK_USE_LATM_AAC) {\n\t\t\t\t\t\t\thintType = GF_RTP_PAYT_LATM;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tcase GF_M4A_AAC_SBR:\n\t\t\t\t\tcase GF_M4A_AAC_PS:\n\t\t\t\t\tcase GF_M4A_AAC_LTP:\n\t\t\t\t\tcase GF_M4A_AAC_SCALABLE:\n\t\t\t\t\tcase GF_M4A_ER_AAC_LC:\n\t\t\t\t\tcase GF_M4A_ER_AAC_LTP:\n\t\t\t\t\tcase GF_M4A_ER_AAC_SCALABLE:\n\t\t\t\t\t\tmpeg4mode = \"AAC\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase GF_M4A_CELP:\n\t\t\t\t\tcase GF_M4A_ER_CELP:\n\t\t\t\t\t\tmpeg4mode = \"CELP\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\trequired_rate = sample_rate;\n\t\t\t\t}\n\t\t\t\t/*MPEG1/2 audio*/\n\t\t\t\telse if ((streamType==GF_STREAM_AUDIO) && ((codecid==GF_CODECID_MPEG2_PART3) || (codecid==GF_CODECID_MPEG_AUDIO))) {\n\t\t\t\t\tGF_ISOSample *samp = NULL;\n\t\t\t\t\tif (!is_crypted)\n\t\t\t\t\t\t samp = gf_isom_get_sample(file, TrackNum, 1, NULL);",
"\t\t\t\t\tif (samp && (samp->dataLength>3)) {\n\t\t\t\t\t\tu32 hdr = GF_4CC((u32)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\tnb_ch = gf_mp3_num_channels(hdr);\n\t\t\t\t\t\thintType = GF_RTP_PAYT_MPEG12_AUDIO;\n\t\t\t\t\t\t/*use official RTP/AVP payload type*/\n\t\t\t\t\t\tOfficialPayloadID = 14;\n\t\t\t\t\t\trequired_rate = 90000;\n\t\t\t\t\t}\n\t\t\t\t\t/*encrypted MP3 must be sent through MPEG-4 generic to signal all ISMACryp stuff*/\n\t\t\t\t\telse {\n\t\t\t\t\t\tu32 sample_rate;\n\t\t\t\t\t\tgf_isom_get_audio_info(file, TrackNum, 1, &sample_rate, &nb_ch, NULL);\n\t\t\t\t\t\trequired_rate = sample_rate;\n\t\t\t\t\t}\n\t\t\t\t\tif (samp)\n\t\t\t\t\t\tgf_isom_sample_del(&samp);",
"\t\t\t\t}\n\t\t\t\t/*QCELP audio*/\n\t\t\t\telse if ((streamType==GF_STREAM_AUDIO) && (codecid==GF_CODECID_QCELP)) {\n\t\t\t\t\thintType = GF_RTP_PAYT_QCELP;\n\t\t\t\t\tOfficialPayloadID = 12;\n\t\t\t\t\trequired_rate = 8000;\n\t\t\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\t\t\tnb_ch = 1;\n\t\t\t\t}\n\t\t\t\t/*EVRC/SVM audio*/\n\t\t\t\telse if ((streamType==GF_STREAM_AUDIO) && ((codecid==GF_CODECID_EVRC) || (codecid==GF_CODECID_SMV)) ) {\n\t\t\t\t\thintType = GF_RTP_PAYT_EVRC_SMV;\n\t\t\t\t\trequired_rate = 8000;\n\t\t\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\t\t\tnb_ch = 1;\n\t\t\t\t}\n\t\t\t\t/*visual streams*/\n\t\t\t\telse if (streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif ((codecid==GF_CODECID_MPEG4_PART2) && esd->decoderConfig->decoderSpecificInfo) {\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\tPL_ID = dsi.VideoPL;\n\t\t\t\t\t}\n\t\t\t\t\t/*MPEG1/2 video*/\n\t\t\t\t\tif ( ((codecid>=GF_CODECID_MPEG2_SIMPLE) && (codecid<=GF_CODECID_MPEG2_422)) || (codecid==GF_CODECID_MPEG1)) {\n\t\t\t\t\t\tif (!is_crypted) {\n\t\t\t\t\t\t\thintType = GF_RTP_PAYT_MPEG12_VIDEO;\n\t\t\t\t\t\t\tOfficialPayloadID = 32;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/*for ISMA*/\n\t\t\t\t\tif (is_crypted) {\n\t\t\t\t\t\t/*that's another pain with ISMACryp, even if no B-frames the DTS is signaled...*/\n\t\t\t\t\t\tif (codecid==GF_CODECID_MPEG4_PART2) force_dts_delta = 22;\n\t\t\t\t\t\telse if ((codecid==GF_CODECID_AVC) || (codecid==GF_CODECID_SVC)) {\n\t\t\t\t\t\t\tflags &= ~GP_RTP_PCK_USE_MULTI;\n\t\t\t\t\t\t\tforce_dts_delta = 22;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tflags |= GP_RTP_PCK_SIGNAL_RAP | GP_RTP_PCK_SIGNAL_TS;\n\t\t\t\t\t}",
"\t\t\t\t\trequired_rate = default_rtp_rate;\n\t\t\t\t}\n\t\t\t\t/*systems streams*/\n\t\t\t\telse if (gf_isom_has_sync_shadows(file, TrackNum) || gf_isom_has_sample_dependency(file, TrackNum)) {\n\t\t\t\t\tflags |= GP_RTP_PCK_SYSTEMS_CAROUSEL;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor*)esd);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_H263:\n\t\t\thintType = GF_RTP_PAYT_H263;\n\t\t\trequired_rate = 90000;\n\t\t\tstreamType = GF_STREAM_VISUAL;\n\t\t\tOfficialPayloadID = 34;\n\t\t\t/*not 100% compliant (short header is missing) but should still work*/\n\t\t\tcodecid = GF_CODECID_MPEG4_PART2;\n\t\t\tPL_ID = 0x01;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_AMR:\n\t\t\trequired_rate = 8000;\n\t\t\thintType = GF_RTP_PAYT_AMR;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\thas_mpeg4_mapping = 0;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_AMR_WB:\n\t\t\trequired_rate = 16000;\n\t\t\thintType = GF_RTP_PAYT_AMR_WB;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\thas_mpeg4_mapping = 0;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_AVC_H264:\n\t\tcase GF_ISOM_SUBTYPE_AVC2_H264:\n\t\tcase GF_ISOM_SUBTYPE_AVC3_H264:\n\t\tcase GF_ISOM_SUBTYPE_AVC4_H264:\n\t\tcase GF_ISOM_SUBTYPE_SVC_H264:\n\t\tcase GF_ISOM_SUBTYPE_MVC_H264:\n\t\t{\n\t\t\tGF_AVCConfig *avcc = gf_isom_avc_config_get(file, TrackNum, 1);\n\t\t\tGF_AVCConfig *svcc = gf_isom_svc_config_get(file, TrackNum, 1);\n\t\t\tGF_AVCConfig *mvcc = gf_isom_mvc_config_get(file, TrackNum, 1);",
"\t\t\tif (!avcc && !svcc && !mvcc) {\n\t\t\t\t*e = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\treturn NULL;\n\t\t\t}",
"\t\t\trequired_rate = 90000;\t/* \"90 kHz clock rate MUST be used\"*/\n\t\t\thintType = GF_RTP_PAYT_H264_AVC;\n\t\t\tif (TrackMediaSubType==GF_ISOM_SUBTYPE_SVC_H264)\n\t\t\t\thintType = GF_RTP_PAYT_H264_SVC;\n\t\t\telse if (TrackMediaSubType==GF_ISOM_SUBTYPE_MVC_H264)\n\t\t\t\thintType = GF_RTP_PAYT_H264_SVC;\n\t\t\tstreamType = GF_STREAM_VISUAL;\n\t\t\tavc_nalu_size = avcc ? avcc->nal_unit_size : svcc ? svcc->nal_unit_size : mvcc->nal_unit_size;\n\t\t\tcodecid = GF_CODECID_AVC;\n\t\t\tPL_ID = 0x0F;\n\t\t\tgf_odf_avc_cfg_del(avcc);\n\t\t\tgf_odf_avc_cfg_del(svcc);\n\t\t}\n\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_HVC1:\n\t\tcase GF_ISOM_SUBTYPE_HEV1:\n\t\tcase GF_ISOM_SUBTYPE_HVC2:\n\t\tcase GF_ISOM_SUBTYPE_HEV2:\n\t\t{\n\t\t\tGF_HEVCConfig *hevcc = gf_isom_hevc_config_get(file, TrackNum, 1);\n\t\t\tif (!hevcc) {\n\t\t\t\t*e = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\trequired_rate = 90000;\t/* \"90 kHz clock rate MUST be used\"*/\n\t\t\thintType = GF_RTP_PAYT_HEVC;\n\t\t\tstreamType = GF_STREAM_VISUAL;\n\t\t\tavc_nalu_size = hevcc->nal_unit_size;\n\t\t\tcodecid = GF_CODECID_HEVC;\n\t\t\tPL_ID = 0x0F;\n\t\t\tflags |= GP_RTP_PCK_USE_MULTI;\n\t\t\tgf_odf_hevc_cfg_del(hevcc);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_QCELP:\n\t\t\trequired_rate = 8000;\n\t\t\thintType = GF_RTP_PAYT_QCELP;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\tcodecid = GF_CODECID_QCELP;\n\t\t\tOfficialPayloadID = 12;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_EVRC:\n\t\tcase GF_ISOM_SUBTYPE_3GP_SMV:\n\t\t\trequired_rate = 8000;\n\t\t\thintType = GF_RTP_PAYT_EVRC_SMV;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\tcodecid = (TrackMediaSubType==GF_ISOM_SUBTYPE_3GP_EVRC) ? GF_CODECID_EVRC : GF_CODECID_SMV;\n\t\t\tnb_ch = 1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_3GP_DIMS:\n#if GPAC_ENABLE_3GPP_DIMS_RTP\n\t\t\thintType = GF_RTP_PAYT_3GPP_DIMS;\n\t\t\tstreamType = GF_STREAM_SCENE;\n#else\n\t\t\thintType = 0;\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[RTP Packetizer] 3GPP DIMS over RTP disabled in build\\n\", streamType));\n#endif\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_AC3:\n\t\t\thintType = GF_RTP_PAYT_AC3;\n\t\t\tstreamType = GF_STREAM_AUDIO;\n\t\t\tgf_isom_get_audio_info(file, TrackNum, 1, NULL, &nb_ch, NULL);\n\t\t\tbreak;\n\t\tcase GF_ISOM_SUBTYPE_MP3:\n\t\t{\n\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, TrackNum, 1, NULL);\n\t\t\tif (samp && (samp->dataLength>3)) {\n\t\t\t\tu32 hdr = GF_4CC((u32)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\tnb_ch = gf_mp3_num_channels(hdr);\n\t\t\t} else {\n\t\t\t\tu32 bps;\n\t\t\t\tgf_isom_get_audio_info(file, TrackNum, 1, &required_rate, &nb_ch, &bps);\n\t\t\t}\n\t\t\thintType = GF_RTP_PAYT_MPEG12_AUDIO;\n\t\t\t/*use official RTP/AVP payload type*/\n\t\t\tOfficialPayloadID = 14;\n\t\t\trequired_rate = 90000;",
"\t\t\tif (samp)\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\t/*ERROR*/\n\t\t\thintType = 0;\n\t\t\tbreak;\n\t\t}\n\t}",
"\t/*not hintable*/\n\tif (!hintType) return NULL;\n\t/*we only support self-contained files for hinting*/\n\tgf_isom_get_data_reference(file, TrackNum, 1, &url, &urn);\n\tif (url || urn) return NULL;",
"\t*e = GF_OUT_OF_MEM;\n\tGF_SAFEALLOC(tmp, GF_RTPHinter);\n\tif (!tmp) return NULL;",
"\t/*override hinter type if requested and possible*/\n\tif (has_mpeg4_mapping && (flags & GP_RTP_PCK_FORCE_MPEG4)) {\n\t\thintType = GF_RTP_PAYT_MPEG4;\n\t\tavc_nalu_size = 0;\n\t}\n\t/*use static payload ID if enabled*/\n\telse if (OfficialPayloadID && (flags & GP_RTP_PCK_USE_STATIC_ID) ) {\n\t\tPayloadID = OfficialPayloadID;\n\t}",
"\ttmp->file = file;\n\ttmp->TrackNum = TrackNum;\n\ttmp->avc_nalu_size = avc_nalu_size;\n\ttmp->nb_chan = nb_ch;",
"\t/*spatial scalability check*/\n\ttmp->has_ctts = gf_isom_has_time_offset(file, TrackNum);",
"\t/*get sample info*/\n\tgf_media_get_sample_average_infos(file, TrackNum, &MinSize, &MaxSize, &avgTS, &maxDTSDelta, &const_dur, &bandwidth);",
"\t/*systems carousel: we need at least IDX and RAP signaling*/\n\tif (flags & GP_RTP_PCK_SYSTEMS_CAROUSEL) {\n\t\tflags |= GP_RTP_PCK_SIGNAL_RAP;\n\t}",
"\t/*update flags in MultiSL*/\n\tif (flags & GP_RTP_PCK_USE_MULTI) {\n\t\tif (MinSize != MaxSize) flags |= GP_RTP_PCK_SIGNAL_SIZE;\n\t\tif (!const_dur) flags |= GP_RTP_PCK_SIGNAL_TS;\n\t}\n\tif (tmp->has_ctts) flags |= GP_RTP_PCK_SIGNAL_TS;",
"\t/*default SL for RTP */\n\tInitSL_RTP(&my_sl);",
"\tmy_sl.timestampResolution = gf_isom_get_media_timescale(file, TrackNum);\n\t/*override clockrate if set*/\n\tif (required_rate) {\n\t\tDouble sc = required_rate;\n\t\tsc /= my_sl.timestampResolution;\n\t\tmaxDTSDelta = (u32) (maxDTSDelta*sc);\n\t\tmy_sl.timestampResolution = required_rate;\n\t}\n\t/*switch to RTP TS*/\n\tmax_ptime = (u32) (max_ptime * my_sl.timestampResolution / 1000);",
"\tmy_sl.AUSeqNumLength = gf_get_bit_size(gf_isom_get_sample_count(file, TrackNum));\n\tif (my_sl.AUSeqNumLength>16) my_sl.AUSeqNumLength=16;",
"\tmy_sl.CUDuration = const_dur;",
"\tif (gf_isom_has_sync_points(file, TrackNum)) {\n\t\tmy_sl.useRandomAccessPointFlag = 1;\n\t} else {\n\t\tmy_sl.useRandomAccessPointFlag = 0;\n\t\tmy_sl.hasRandomAccessUnitsOnlyFlag = 1;\n\t}",
"\tif (is_crypted) {\n\t\tBool use_sel_enc;\n\t\tgf_isom_get_ismacryp_info(file, TrackNum, 1, NULL, NULL, NULL, NULL, NULL, &use_sel_enc, &IV_length, &KI_length);\n\t\tif (use_sel_enc) flags |= GP_RTP_PCK_SELECTIVE_ENCRYPTION;\n\t}",
"\t// in case a different timescale was provided\n\ttmp->OrigTimeScale = gf_isom_get_media_timescale(file, TrackNum);\n\ttmp->rtp_p = gf_rtp_builder_new(hintType, &my_sl, flags, tmp,\n\t MP4T_OnNewPacket, MP4T_OnPacketDone,\n\t /*if copy, no data ref*/\n\t copy_media ? NULL : MP4T_OnDataRef,\n\t MP4T_OnData);",
"\t//init the builder\n\tgf_rtp_builder_init(tmp->rtp_p, PayloadID, Path_MTU, max_ptime,\n\t streamType, codecid, PL_ID, MinSize, MaxSize, avgTS, maxDTSDelta, IV_length, KI_length, mpeg4mode);",
"\t/*ISMA compliance is a pain...*/\n\tif (force_dts_delta) tmp->rtp_p->slMap.DTSDeltaLength = force_dts_delta;",
"\n\t/*\t\tHint Track Setup\t*/\n\ttmp->TrackID = gf_isom_get_track_id(file, TrackNum);\n\ttmp->HintID = tmp->TrackID + 65535;\n\twhile (gf_isom_get_track_by_id(file, tmp->HintID)) tmp->HintID++;",
"\ttmp->HintTrack = gf_isom_new_track(file, tmp->HintID, GF_ISOM_MEDIA_HINT, my_sl.timestampResolution);\n\tgf_isom_setup_hint_track(file, tmp->HintTrack, GF_ISOM_HINT_RTP);\n\t/*create a hint description*/\n\tgf_isom_new_hint_description(file, tmp->HintTrack, -1, -1, 0, &descIndex);\n\tgf_isom_rtp_set_timescale(file, tmp->HintTrack, descIndex, my_sl.timestampResolution);",
"\tif (hintType==GF_RTP_PAYT_MPEG4) {\n\t\ttmp->rtp_p->slMap.CodecID = codecid;\n\t\t/*set this SL for extraction.*/\n\t\tgf_isom_set_extraction_slc(file, TrackNum, 1, &my_sl);\n\t}\n\ttmp->bandwidth = bandwidth;",
"\t/*set interleaving*/\n\tgf_isom_set_track_interleaving_group(file, TrackNum, InterleaveGroupID);\n\tif (!copy_media) {\n\t\t/*if we don't copy data set hint track and media track in the same group*/\n\t\tgf_isom_set_track_interleaving_group(file, tmp->HintTrack, InterleaveGroupID);\n\t} else {\n\t\tgf_isom_set_track_interleaving_group(file, tmp->HintTrack, InterleaveGroupID + OFFSET_HINT_GROUP_ID);\n\t}\n\t/*use user-secified priority*/\n\tInterleaveGroupPriority*=2;\n\tgf_isom_set_track_priority_in_group(file, TrackNum, InterleaveGroupPriority+1);\n\tgf_isom_set_track_priority_in_group(file, tmp->HintTrack, InterleaveGroupPriority);",
"#if 0\n#endif\n\t*e = GF_OK;\n\treturn tmp;\n}",
"GF_EXPORT\nGF_Err gf_hinter_track_force_no_offsets(GF_RTPHinter *tkHinter)\n{\n\tGF_Err e;\n\tif (!tkHinter) return GF_BAD_PARAM;\n\te = gf_isom_rtp_set_time_offset(tkHinter->file, tkHinter->HintTrack, 1, 0);\n\tif (e) return e;\n\treturn gf_isom_rtp_set_time_sequence_offset(tkHinter->file, tkHinter->HintTrack, 1, 0);\n}",
"GF_EXPORT\nu32 gf_hinter_track_get_bandwidth(GF_RTPHinter *tkHinter)\n{\n\treturn tkHinter->bandwidth;\n}",
"GF_EXPORT\nu32 gf_hinter_track_get_flags(GF_RTPHinter *tkHinter)\n{\n\treturn tkHinter->rtp_p->flags;\n}\nGF_EXPORT\nvoid gf_hinter_track_get_payload_name(GF_RTPHinter *tkHinter, char *payloadName)\n{\n\tchar mediaName[30];\n\tgf_rtp_builder_get_payload_name(tkHinter->rtp_p, payloadName, mediaName);\n}",
"GF_EXPORT\nvoid gf_hinter_track_del(GF_RTPHinter *tkHinter)\n{\n\tif (!tkHinter) return;",
"\tif (tkHinter->rtp_p) gf_rtp_builder_del(tkHinter->rtp_p);\n\tgf_free(tkHinter);\n}",
"GF_EXPORT\nGF_Err gf_hinter_track_process(GF_RTPHinter *tkHint)\n{\n\tGF_Err e;\n\tu32 i, descIndex, duration;\n\tu64 ts;\n\tu8 PadBits;\n\tGF_Fraction ft;\n\tGF_ISOSample *samp;",
"\ttkHint->HintSample = tkHint->RTPTime = 0;",
"\ttkHint->TotalSample = gf_isom_get_sample_count(tkHint->file, tkHint->TrackNum);\n\tft.num = tkHint->rtp_p->sl_config.timestampResolution;\n\tft.den = tkHint->OrigTimeScale;",
"\te = GF_OK;\n\tfor (i=0; i<tkHint->TotalSample; i++) {\n\t\tsamp = gf_isom_get_sample(tkHint->file, tkHint->TrackNum, i+1, &descIndex);\n\t\tif (!samp) return gf_isom_last_error(tkHint->file);",
"\t\t//setup SL\n\t\ttkHint->CurrentSample = i + 1;",
"\t\t/*keep same AU indicator if sync shadow - TODO FIXME: this assumes shadows are placed interleaved with\n\t\tthe track content which is the case for GPAC scene carousel generation, but may not always be true*/\n\t\tif (samp->IsRAP==RAP_REDUNDANT) {\n\t\t\ttkHint->rtp_p->sl_header.AU_sequenceNumber -= 1;\n\t\t\tsamp->IsRAP = RAP;\n\t\t}",
"\t\tts = ft.num * (samp->DTS+samp->CTS_Offset) / ft.den;\n\t\ttkHint->rtp_p->sl_header.compositionTimeStamp = ts;",
"\t\tts = ft.num * samp->DTS / ft.den;\n\t\ttkHint->rtp_p->sl_header.decodingTimeStamp = ts;\n\t\ttkHint->rtp_p->sl_header.randomAccessPointFlag = samp->IsRAP;",
"\t\ttkHint->base_offset_in_sample = 0;\n\t\t/*crypted*/\n\t\tif (tkHint->rtp_p->slMap.IV_length) {\n\t\t\tGF_ISMASample *s = gf_isom_get_ismacryp_sample(tkHint->file, tkHint->TrackNum, samp, descIndex);\n\t\t\t/*one byte take for selective_enc flag*/\n\t\t\tif (s->flags & GF_ISOM_ISMA_USE_SEL_ENC) tkHint->base_offset_in_sample += 1;\n\t\t\tif (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) tkHint->base_offset_in_sample += s->IV_length + s->KI_length;\n\t\t\tgf_free(samp->data);\n\t\t\tsamp->data = s->data;\n\t\t\tsamp->dataLength = s->dataLength;\n\t\t\tgf_rtp_builder_set_cryp_info(tkHint->rtp_p, s->IV, (char*)s->key_indicator, (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) ? 1 : 0);\n\t\t\ts->data = NULL;\n\t\t\ts->dataLength = 0;\n\t\t\tgf_isom_ismacryp_delete_sample(s);\n\t\t}",
"\t\tif (tkHint->rtp_p->sl_config.usePaddingFlag) {\n\t\t\tgf_isom_get_sample_padding_bits(tkHint->file, tkHint->TrackNum, i+1, &PadBits);\n\t\t\ttkHint->rtp_p->sl_header.paddingBits = PadBits;\n\t\t} else {\n\t\t\ttkHint->rtp_p->sl_header.paddingBits = 0;\n\t\t}",
"\t\tduration = gf_isom_get_sample_duration(tkHint->file, tkHint->TrackNum, i+1);\n//\t\tts = (u32) (ft * (s64) (duration));",
"\t\t/*unpack nal units*/\n\t\tif (tkHint->avc_nalu_size) {\n\t\t\tu32 v, size;\n\t\t\tu32 remain = samp->dataLength;\n\t\t\tchar *ptr = samp->data;",
"\t\t\ttkHint->rtp_p->sl_header.accessUnitStartFlag = 1;\n\t\t\ttkHint->rtp_p->sl_header.accessUnitEndFlag = 0;\n\t\t\twhile (remain) {\n\t\t\t\tsize = 0;\n\t\t\t\tv = tkHint->avc_nalu_size;\n\t\t\t\tif (v>remain) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size length is %d but only %d bytes left in sample %d\\n\", v, remain, tkHint->CurrentSample));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\twhile (v) {\n\t\t\t\t\tsize |= (u8) *ptr;\n\t\t\t\t\tptr++;\n\t\t\t\t\tremain--;\n\t\t\t\t\tv-=1;\n\t\t\t\t\tif (v) size<<=8;\n\t\t\t\t}\n\t\t\t\ttkHint->base_offset_in_sample = samp->dataLength-remain;\n\t\t\t\tif (remain < size) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size is %d but only %d bytes left in sample %d\\n\", size, remain, tkHint->CurrentSample));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tremain -= size;\n\t\t\t\ttkHint->rtp_p->sl_header.accessUnitEndFlag = remain ? 0 : 1;",
"\t\t\t\tif (!size) {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] Broken AVC nalu encapsulation: NALU size is 0, ignoring it\\n\", size));\n\t\t\t\t} else {\n\t\t\t\t\te = gf_rtp_builder_process(tkHint->rtp_p, ptr, size, (u8) !remain, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) );\n\t\t\t\t\tptr += size;\n\t\t\t\t}",
"\t\t\t\ttkHint->rtp_p->sl_header.accessUnitStartFlag = 0;\n\t\t\t}\n\t\t} else {\n\t\t\te = gf_rtp_builder_process(tkHint->rtp_p, samp->data, samp->dataLength, 1, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) );\n\t\t}\n\t\ttkHint->rtp_p->sl_header.packetSequenceNumber += 1;",
"\t\t//signal some progress\n\t\tgf_set_progress(\"Hinting\", tkHint->CurrentSample, tkHint->TotalSample);",
"\t\ttkHint->rtp_p->sl_header.AU_sequenceNumber += 1;\n\t\tgf_isom_sample_del(&samp);",
"\t\tif (e) return e;\n\t}",
"\t//flush\n\tgf_rtp_builder_process(tkHint->rtp_p, NULL, 0, 1, 0, 0, 0);",
"\tgf_isom_end_hint_sample(tkHint->file, tkHint->HintTrack, (u8) tkHint->SampleIsRAP);\n\treturn GF_OK;\n}",
"static u32 write_nalu_config_array(char *sdpLine, GF_List *nalus)\n{\n\tu32 i, count, b64s;\n\tchar b64[200];",
"\tcount = gf_list_count(nalus);\n\tfor (i=0; i<count; i++) {\n\t\tGF_NALUFFParam *sl = (GF_NALUFFParam *)gf_list_get(nalus, i);\n\t\tb64s = gf_base64_encode(sl->data, sl->size, b64, 200);\n\t\tb64[b64s]=0;\n\t\tstrcat(sdpLine, b64);\n\t\tif (i+1<count) strcat(sdpLine, \",\");\n\t}\n\treturn count;\n}",
"static void write_avc_config(char *sdpLine, GF_AVCConfig *avcc, GF_AVCConfig *svcc)\n{\n\tu32 count = 0;",
"\tif (avcc) count += gf_list_count(avcc->sequenceParameterSets) + gf_list_count(avcc->pictureParameterSets) + gf_list_count(avcc->sequenceParameterSetExtensions);\n\tif (svcc) count += gf_list_count(svcc->sequenceParameterSets) + gf_list_count(svcc->pictureParameterSets);\n\tif (!count) return;",
"\tstrcat(sdpLine, \"; sprop-parameter-sets=\");",
"\tif (avcc) {\n\t\tcount = write_nalu_config_array(sdpLine, avcc->sequenceParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t\tcount = write_nalu_config_array(sdpLine, avcc->sequenceParameterSetExtensions);\n\t\tif (count) strcat(sdpLine, \",\");\n\t\tcount = write_nalu_config_array(sdpLine, avcc->pictureParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t}",
"\tif (svcc) {\n\t\tcount = write_nalu_config_array(sdpLine, svcc->sequenceParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t\tcount = write_nalu_config_array(sdpLine, svcc->pictureParameterSets);\n\t\tif (count) strcat(sdpLine, \",\");\n\t}\n\tcount = (u32) strlen(sdpLine);\n\tif (sdpLine[count-1] == ',')\n\t\tsdpLine[count-1] = 0;\n}",
"GF_EXPORT\nGF_Err gf_hinter_track_finalize(GF_RTPHinter *tkHint, Bool AddSystemInfo)\n{\n\tu32 Width, Height;\n\tGF_ESD *esd;\n\tchar sdpLine[20000];\n\tchar mediaName[30], payloadName[30];\n u32 mtype;",
"\tWidth = Height = 0;\n\tgf_isom_sdp_clean_track(tkHint->file, tkHint->TrackNum);\n mtype = gf_isom_get_media_type(tkHint->file, tkHint->TrackNum);\n if (gf_isom_is_video_handler_type(mtype))\n\t\tgf_isom_get_visual_info(tkHint->file, tkHint->TrackNum, 1, &Width, &Height);",
"\tgf_rtp_builder_get_payload_name(tkHint->rtp_p, payloadName, mediaName);",
"\t/*TODO- extract out of rtp_p for future live tools*/\n\tsprintf(sdpLine, \"m=%s 0 RTP/%s %d\", mediaName, tkHint->rtp_p->slMap.IV_length ? \"SAVP\" : \"AVP\", tkHint->rtp_p->PayloadType);\n\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\tif (tkHint->bandwidth) {\n\t\tsprintf(sdpLine, \"b=AS:%d\", tkHint->bandwidth);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\tif (tkHint->nb_chan) {\n\t\tsprintf(sdpLine, \"a=rtpmap:%d %s/%d/%d\", tkHint->rtp_p->PayloadType, payloadName, tkHint->rtp_p->sl_config.timestampResolution, tkHint->nb_chan);\n\t} else {\n\t\tsprintf(sdpLine, \"a=rtpmap:%d %s/%d\", tkHint->rtp_p->PayloadType, payloadName, tkHint->rtp_p->sl_config.timestampResolution);\n\t}\n\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t/*control for MPEG-4*/\n\tif (AddSystemInfo) {\n\t\tsprintf(sdpLine, \"a=mpeg4-esid:%d\", gf_isom_get_track_id(tkHint->file, tkHint->TrackNum));\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*control for QTSS/DSS*/\n\tsprintf(sdpLine, \"a=control:trackID=%d\", gf_isom_get_track_id(tkHint->file, tkHint->HintTrack));\n\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);",
"\t/*H263 extensions*/\n\tif (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H263) {\n\t\tsprintf(sdpLine, \"a=cliprect:0,0,%d,%d\", Height, Width);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*AMR*/\n\telse if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_AMR) || (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_AMR_WB)) {\n\t\tsprintf(sdpLine, \"a=fmtp:%d octet-align=1\", tkHint->rtp_p->PayloadType);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*Text*/\n\telse if (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_3GPP_TEXT) {\n\t\tu32 w, h, i, m_w, m_h;\n\t\ts32 tx, ty;\n\t\ts16 l;",
"\t\tgf_isom_get_track_layout_info(tkHint->file, tkHint->TrackNum, &w, &h, &tx, &ty, &l);\n\t\tm_w = w;\n\t\tm_h = h;\n\t\tfor (i=0; i<gf_isom_get_track_count(tkHint->file); i++) {\n\t\t\tswitch (gf_isom_get_media_type(tkHint->file, i+1)) {\n\t\t\tcase GF_ISOM_MEDIA_SCENE:\n\t\t\tcase GF_ISOM_MEDIA_VISUAL:\n\t\t\tcase GF_ISOM_MEDIA_AUXV:\n\t\t\tcase GF_ISOM_MEDIA_PICT:\n\t\t\t\tgf_isom_get_track_layout_info(tkHint->file, i+1, &w, &h, &tx, &ty, &l);\n\t\t\t\tif (w>m_w) m_w = w;\n\t\t\t\tif (h>m_h) m_h = h;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}",
"\t\tgf_media_format_ttxt_sdp(tkHint->rtp_p, payloadName, sdpLine, w, h, tx, ty, l, m_w, m_h, NULL);",
"\t\tstrcat(sdpLine, \"; tx3g=\");\n\t\tfor (i=0; i<gf_isom_get_sample_description_count(tkHint->file, tkHint->TrackNum); i++) {\n\t\t\tu8 *tx3g;\n\t\t\tchar buffer[2000];\n\t\t\tu32 tx3g_len, len;\n\t\t\tgf_isom_text_get_encoded_tx3g(tkHint->file, tkHint->TrackNum, i+1, GF_RTP_TX3G_SIDX_OFFSET, &tx3g, &tx3g_len);\n\t\t\tlen = gf_base64_encode(tx3g, tx3g_len, buffer, 2000);\n\t\t\tgf_free(tx3g);\n\t\t\tbuffer[len] = 0;\n\t\t\tif (i) strcat(sdpLine, \", \");\n\t\t\tstrcat(sdpLine, buffer);\n\t\t}\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*EVRC/SMV in non header-free mode*/\n\telse if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_EVRC_SMV) && (tkHint->rtp_p->auh_size>1)) {\n\t\tsprintf(sdpLine, \"a=fmtp:%d maxptime=%d\", tkHint->rtp_p->PayloadType, tkHint->rtp_p->auh_size*20);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*H264/AVC*/\n\telse if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H264_AVC) || (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H264_SVC)) {\n\t\tGF_AVCConfig *avcc = gf_isom_avc_config_get(tkHint->file, tkHint->TrackNum, 1);\n\t\tGF_AVCConfig *svcc = gf_isom_svc_config_get(tkHint->file, tkHint->TrackNum, 1);\n\t\t/*TODO - check syntax for SVC (might be some extra signaling)*/",
"\t\tif (avcc) {\n\t\t\tsprintf(sdpLine, \"a=fmtp:%d profile-level-id=%02X%02X%02X; packetization-mode=1\", tkHint->rtp_p->PayloadType, avcc->AVCProfileIndication, avcc->profile_compatibility, avcc->AVCLevelIndication);\n\t\t} else {\n\t\t\tif (!svcc)\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\tsprintf(sdpLine, \"a=fmtp:%d profile-level-id=%02X%02X%02X; packetization-mode=1\", tkHint->rtp_p->PayloadType, svcc->AVCProfileIndication, svcc->profile_compatibility, svcc->AVCLevelIndication);\n\t\t}",
"\t\twrite_avc_config(sdpLine, avcc, svcc);",
"\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t\tgf_odf_avc_cfg_del(avcc);\n\t\tgf_odf_avc_cfg_del(svcc);\n\t}\n\t/*MPEG-4 decoder config*/\n\telse if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_MPEG4) {\n\t\tesd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1);",
"\t\tif (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) {\n\t\t\tgf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength);\n\t\t} else {\n\t\t\tgf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, NULL, 0);\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);",
"\t\tif (tkHint->rtp_p->slMap.IV_length) {\n\t\t\tconst char *kms;\n\t\t\tgf_isom_get_ismacryp_info(tkHint->file, tkHint->TrackNum, 1, NULL, NULL, NULL, NULL, &kms, NULL, NULL, NULL);\n\t\t\tif (!strnicmp(kms, \"(key)\", 5) || !strnicmp(kms, \"(ipmp)\", 6) || !strnicmp(kms, \"(uri)\", 5)) {\n\t\t\t\tstrcat(sdpLine, \"; ISMACrypKey=\");\n\t\t\t} else {\n\t\t\t\tstrcat(sdpLine, \"; ISMACrypKey=(uri)\");\n\t\t\t}\n\t\t\tstrcat(sdpLine, kms);\n\t\t}",
"\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\t/*MPEG-4 Audio LATM*/\n\telse if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_LATM) {\n\t\tGF_BitStream *bs;\n\t\tu8 *config_bytes;\n\t\tu32 config_size;",
"\t\t/* form config string */\n\t\tbs = gf_bs_new(NULL, 32, GF_BITSTREAM_WRITE);\n\t\tgf_bs_write_int(bs, 0, 1); /* AudioMuxVersion */\n\t\tgf_bs_write_int(bs, 1, 1); /* all streams same time */\n\t\tgf_bs_write_int(bs, 0, 6); /* numSubFrames */\n\t\tgf_bs_write_int(bs, 0, 4); /* numPrograms */\n\t\tgf_bs_write_int(bs, 0, 3); /* numLayer */",
"\t\t/* audio-specific config */\n\t\tesd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1);\n\t\tif (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo) {\n\t\t\t/*PacketVideo patch: don't signal SBR and PS stuff, not allowed in LATM with audioMuxVersion=0*/\n\t\t\tgf_bs_write_data(bs, esd->decoderConfig->decoderSpecificInfo->data, MIN(esd->decoderConfig->decoderSpecificInfo->dataLength, 2) );\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);",
"\t\t/* other data */\n\t\tgf_bs_write_int(bs, 0, 3); /* frameLengthType */\n\t\tgf_bs_write_int(bs, 0xff, 8); /* latmBufferFullness */\n\t\tgf_bs_write_int(bs, 0, 1); /* otherDataPresent */\n\t\tgf_bs_write_int(bs, 0, 1); /* crcCheckPresent */\n\t\tgf_bs_get_content(bs, &config_bytes, &config_size);\n\t\tgf_bs_del(bs);",
"\t\tgf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, config_bytes, config_size);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t\tgf_free(config_bytes);\n\t}\n#if GPAC_ENABLE_3GPP_DIMS_RTP\n\t/*3GPP DIMS*/\n\telse if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_3GPP_DIMS) {\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(tkHint->file, tkHint->TrackNum, 1, &Width, &Height);",
"\t\tgf_isom_get_dims_description(tkHint->file, tkHint->TrackNum, 1, &dims);\n\t\tsprintf(sdpLine, \"a=fmtp:%d Version-profile=%d\", tkHint->rtp_p->PayloadType, dims.profile);\n\t\tif (! dims.fullRequestHost) {\n\t\t\tchar fmt[200];\n\t\t\tstrcat(sdpLine, \";useFullRequestHost=0\");\n\t\t\tsprintf(fmt, \";pathComponents=%d\", dims.pathComponents);\n\t\t\tstrcat(sdpLine, fmt);\n\t\t}\n\t\tif (!dims.streamType) strcat(sdpLine, \";stream-type=secondary\");\n\t\tif (dims.containsRedundant == 1) strcat(sdpLine, \";contains-redundant=main\");\n\t\telse if (dims.containsRedundant == 2) strcat(sdpLine, \";contains-redundant=redundant\");",
"\t\tif (dims.textEncoding && strlen(dims.textEncoding)) {\n\t\t\tstrcat(sdpLine, \";text-encoding=\");\n\t\t\tstrcat(sdpLine, dims.textEncoding);\n\t\t}\n\t\tif (dims.contentEncoding && strlen(dims.contentEncoding)) {\n\t\t\tstrcat(sdpLine, \";content-coding=\");\n\t\t\tstrcat(sdpLine, dims.contentEncoding);\n\t\t}\n\t\tif (dims.contentEncoding && dims.content_script_types && strlen(dims.content_script_types) ) {\n\t\t\tstrcat(sdpLine, \";content-script-types=\");\n\t\t\tstrcat(sdpLine, dims.contentEncoding);\n\t\t}\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n#endif\n\t/*extensions for some mobile phones*/\n\tif (Width && Height) {\n\t\tsprintf(sdpLine, \"a=framesize:%d %d-%d\", tkHint->rtp_p->PayloadType, Width, Height);\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}",
"\tesd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1);\n\tif (esd && esd->decoderConfig && (esd->decoderConfig->rvc_config || esd->decoderConfig->predefined_rvc_config)) {\n\t\tif (esd->decoderConfig->predefined_rvc_config) {\n\t\t\tsprintf(sdpLine, \"a=rvc-config-predef:%d\", esd->decoderConfig->predefined_rvc_config);\n\t\t} else {\n\t\t\t/*temporary ...*/\n\t\t\tif ((esd->decoderConfig->objectTypeIndication==GF_CODECID_AVC) || (esd->decoderConfig->objectTypeIndication==GF_CODECID_SVC)) {\n\t\t\t\tsprintf(sdpLine, \"a=rvc-config:%s\", \"http://download.tsi.telecom-paristech.fr/gpac/RVC/rvc_config_avc.xml\");\n\t\t\t} else {\n\t\t\t\tsprintf(sdpLine, \"a=rvc-config:%s\", \"http://download.tsi.telecom-paristech.fr/gpac/RVC/rvc_config_sp.xml\");\n\t\t\t}\n\t\t}\n\t\tgf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine);\n\t}\n\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);",
"\tgf_isom_set_track_enabled(tkHint->file, tkHint->HintTrack, GF_TRUE);\n\treturn GF_OK;\n}",
"GF_EXPORT\nBool gf_hinter_can_embbed_data(u8 *data, u32 data_size, u32 streamType)\n{\n\tchar data64[5000];\n\tu32 size64;",
"\tsize64 = gf_base64_encode(data, data_size, data64, 5000);\n\tif (!size64) return 0;\n\tswitch (streamType) {\n\tcase GF_STREAM_OD:\n\t\tsize64 += (u32) strlen(\"data:application/mpeg4-od-au;base64,\");\n\t\tbreak;\n\tcase GF_STREAM_SCENE:\n\t\tsize64 += (u32) strlen(\"data:application/mpeg4-bifs-au;base64,\");\n\t\tbreak;\n\tdefault:\n\t\t/*NOT NORMATIVE*/\n\t\tsize64 += (u32) strlen(\"data:application/mpeg4-es-au;base64,\");\n\t\tbreak;\n\t}\n\tif (size64>=255) return 0;\n\treturn 1;\n}",
"\nGF_EXPORT\nGF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];",
"\n\tgf_isom_sdp_clean(file);",
"\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);",
"\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;",
"\todT = sceneT = 0;\n\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\tif (!gf_isom_is_track_in_root_od(file, i+1)) continue;\n\t\tswitch (gf_isom_get_media_type(file,i+1)) {\n\t\tcase GF_ISOM_MEDIA_OD:\n\t\t\todT = i+1;\n\t\t\tbreak;\n\t\tcase GF_ISOM_MEDIA_SCENE:\n\t\t\tsceneT = i+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tremove_ocr = 0;\n\tif (IOD_Profile == GF_SDP_IOD_ISMA_STRICT) {\n\t\tIOD_Profile = GF_SDP_IOD_ISMA;\n\t\tremove_ocr = 1;\n\t}",
"\t/*if we want ISMA like iods, we need at least BIFS */\n\tif ( (IOD_Profile == GF_SDP_IOD_ISMA) && !sceneT ) return GF_BAD_PARAM;",
"\t/*do NOT change PLs, we assume they are correct*/\n\tiod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file);\n\tif (!iod) return GF_NOT_SUPPORTED;",
"\t/*rewrite an IOD with good SL config - embbed data if possible*/\n\tif (IOD_Profile == GF_SDP_IOD_ISMA) {\n\t\tGF_ESD *esd;\n\t\tBool is_ok = 1;\n\t\twhile (gf_list_count(iod->ESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}",
"\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);",
"\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);",
"\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;",
"\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}",
"\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {",
"\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);",
"\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;",
"\t\tgf_list_add(iod->ESDescriptors, esd);",
"\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; i<gf_isom_get_track_count(file); i++) {\n\t\t\t\tesd = gf_isom_get_esd(file, i+1, 1);\n\t\t\t\tif (!esd) continue;\n\t\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}",
"\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);",
"\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);",
"\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);",
"\treturn GF_OK;\n}",
"\n#endif /*GPAC_DISABLE_ISOM_HINTING*/",
"#endif /*GPAC_DISABLE_ISOM*/"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [798], "buggy_code_start_loc": [796], "filenames": ["src/media_tools/isom_hinter.c"], "fixing_code_end_loc": [802], "fixing_code_start_loc": [796], "message": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is heap-based buffer overflow in the function gp_rtp_builder_do_avc() in ietf/rtp_pck_mpeg4.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gpac:gpac:0.8.0:*:*:*:*:*:*:*", "matchCriteriaId": "93EEFCFD-7417-40E6-84BF-4EA630F2A8A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"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": "An issue was discovered in GPAC version 0.8.0 and 1.0.1. There is heap-based buffer overflow in the function gp_rtp_builder_do_avc() in ietf/rtp_pck_mpeg4.c."}, {"lang": "es", "value": "Se detect\u00f3 un problema en GPAC versiones 0.8.0 y 1.0.1. Se presenta un desbordamiento del b\u00fafer en la regi\u00f3n heap de la memoria en la funci\u00f3n gp_rtp_builder_do_avc() en el archivo ietf/rtp_pck_mpeg4.c"}], "evaluatorComment": null, "id": "CVE-2020-35979", "lastModified": "2021-04-23T19:53:24.550", "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": null, "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": "2021-04-21T16:15:08.647", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/commit/b15020f54aff24aaeb64b80771472be8e64a7adc"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/gpac/gpac/issues/1662"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/gpac/gpac/commit/b15020f54aff24aaeb64b80771472be8e64a7adc"}, "type": "CWE-787"}
| 313
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * APEI Error INJection support\n *\n * EINJ provides a hardware error injection mechanism, this is useful\n * for debugging and testing of other APEI and RAS features.\n *\n * For more information about EINJ, please refer to ACPI Specification\n * version 4.0, section 17.5.\n *\n * Copyright 2009-2010 Intel Corp.\n * Author: Huang Ying <ying.huang@intel.com>\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 version\n * 2 as published by the Free Software Foundation.\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 */",
"#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/init.h>\n#include <linux/io.h>\n#include <linux/debugfs.h>\n#include <linux/seq_file.h>\n#include <linux/nmi.h>\n#include <linux/delay.h>\n#include <linux/mm.h>",
"",
"#include <asm/unaligned.h>",
"#include \"apei-internal.h\"",
"#define EINJ_PFX \"EINJ: \"",
"#define SPIN_UNIT\t\t100\t\t\t/* 100ns */\n/* Firmware should respond within 1 milliseconds */\n#define FIRMWARE_TIMEOUT\t(1 * NSEC_PER_MSEC)\n#define ACPI5_VENDOR_BIT\tBIT(31)\n#define MEM_ERROR_MASK\t\t(ACPI_EINJ_MEMORY_CORRECTABLE | \\\n\t\t\t\tACPI_EINJ_MEMORY_UNCORRECTABLE | \\\n\t\t\t\tACPI_EINJ_MEMORY_FATAL)",
"/*\n * ACPI version 5 provides a SET_ERROR_TYPE_WITH_ADDRESS action.\n */\nstatic int acpi5;",
"struct set_error_type_with_address {\n\tu32\ttype;\n\tu32\tvendor_extension;\n\tu32\tflags;\n\tu32\tapicid;\n\tu64\tmemory_address;\n\tu64\tmemory_address_range;\n\tu32\tpcie_sbdf;\n};\nenum {\n\tSETWA_FLAGS_APICID = 1,\n\tSETWA_FLAGS_MEM = 2,\n\tSETWA_FLAGS_PCIE_SBDF = 4,\n};",
"/*\n * Vendor extensions for platform specific operations\n */\nstruct vendor_error_type_extension {\n\tu32\tlength;\n\tu32\tpcie_sbdf;\n\tu16\tvendor_id;\n\tu16\tdevice_id;\n\tu8\trev_id;\n\tu8\treserved[3];\n};",
"static u32 notrigger;",
"static u32 vendor_flags;\nstatic struct debugfs_blob_wrapper vendor_blob;\nstatic char vendor_dev[64];",
"/*\n * Some BIOSes allow parameters to the SET_ERROR_TYPE entries in the\n * EINJ table through an unpublished extension. Use with caution as\n * most will ignore the parameter and make their own choice of address\n * for error injection. This extension is used only if\n * param_extension module parameter is specified.\n */\nstruct einj_parameter {\n\tu64 type;\n\tu64 reserved1;\n\tu64 reserved2;\n\tu64 param1;\n\tu64 param2;\n};",
"#define EINJ_OP_BUSY\t\t\t0x1\n#define EINJ_STATUS_SUCCESS\t\t0x0\n#define EINJ_STATUS_FAIL\t\t0x1\n#define EINJ_STATUS_INVAL\t\t0x2",
"#define EINJ_TAB_ENTRY(tab)\t\t\t\t\t\t\\\n\t((struct acpi_whea_header *)((char *)(tab) +\t\t\t\\\n\t\t\t\t sizeof(struct acpi_table_einj)))",
"static bool param_extension;\nmodule_param(param_extension, bool, 0);",
"static struct acpi_table_einj *einj_tab;",
"static struct apei_resources einj_resources;",
"static struct apei_exec_ins_type einj_ins_type[] = {\n\t[ACPI_EINJ_READ_REGISTER] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_read_register,\n\t},\n\t[ACPI_EINJ_READ_REGISTER_VALUE] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_read_register_value,\n\t},\n\t[ACPI_EINJ_WRITE_REGISTER] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_write_register,\n\t},\n\t[ACPI_EINJ_WRITE_REGISTER_VALUE] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_write_register_value,\n\t},\n\t[ACPI_EINJ_NOOP] = {\n\t\t.flags = 0,\n\t\t.run = apei_exec_noop,\n\t},\n};",
"/*\n * Prevent EINJ interpreter to run simultaneously, because the\n * corresponding firmware implementation may not work properly when\n * invoked simultaneously.\n */\nstatic DEFINE_MUTEX(einj_mutex);",
"static void *einj_param;",
"static void einj_exec_ctx_init(struct apei_exec_context *ctx)\n{\n\tapei_exec_ctx_init(ctx, einj_ins_type, ARRAY_SIZE(einj_ins_type),\n\t\t\t EINJ_TAB_ENTRY(einj_tab), einj_tab->entries);\n}",
"static int __einj_get_available_error_type(u32 *type)\n{\n\tstruct apei_exec_context ctx;\n\tint rc;",
"\teinj_exec_ctx_init(&ctx);\n\trc = apei_exec_run(&ctx, ACPI_EINJ_GET_ERROR_TYPE);\n\tif (rc)\n\t\treturn rc;\n\t*type = apei_exec_ctx_get_output(&ctx);",
"\treturn 0;\n}",
"/* Get error injection capabilities of the platform */\nstatic int einj_get_available_error_type(u32 *type)\n{\n\tint rc;",
"\tmutex_lock(&einj_mutex);\n\trc = __einj_get_available_error_type(type);\n\tmutex_unlock(&einj_mutex);",
"\treturn rc;\n}",
"static int einj_timedout(u64 *t)\n{\n\tif ((s64)*t < SPIN_UNIT) {\n\t\tpr_warning(FW_WARN EINJ_PFX\n\t\t\t \"Firmware does not respond in time\\n\");\n\t\treturn 1;\n\t}\n\t*t -= SPIN_UNIT;\n\tndelay(SPIN_UNIT);\n\ttouch_nmi_watchdog();\n\treturn 0;\n}",
"static void check_vendor_extension(u64 paddr,\n\t\t\t\t struct set_error_type_with_address *v5param)\n{\n\tint\toffset = v5param->vendor_extension;\n\tstruct\tvendor_error_type_extension *v;\n\tu32\tsbdf;",
"\tif (!offset)\n\t\treturn;\n\tv = acpi_os_map_iomem(paddr + offset, sizeof(*v));\n\tif (!v)\n\t\treturn;\n\tsbdf = v->pcie_sbdf;\n\tsprintf(vendor_dev, \"%x:%x:%x.%x vendor_id=%x device_id=%x rev_id=%x\\n\",\n\t\tsbdf >> 24, (sbdf >> 16) & 0xff,\n\t\t(sbdf >> 11) & 0x1f, (sbdf >> 8) & 0x7,\n\t\t v->vendor_id, v->device_id, v->rev_id);\n\tacpi_os_unmap_iomem(v, sizeof(*v));\n}",
"static void *einj_get_parameter_address(void)\n{\n\tint i;\n\tu64 pa_v4 = 0, pa_v5 = 0;\n\tstruct acpi_whea_header *entry;",
"\tentry = EINJ_TAB_ENTRY(einj_tab);\n\tfor (i = 0; i < einj_tab->entries; i++) {\n\t\tif (entry->action == ACPI_EINJ_SET_ERROR_TYPE &&\n\t\t entry->instruction == ACPI_EINJ_WRITE_REGISTER &&\n\t\t entry->register_region.space_id ==\n\t\t ACPI_ADR_SPACE_SYSTEM_MEMORY)\n\t\t\tpa_v4 = get_unaligned(&entry->register_region.address);\n\t\tif (entry->action == ACPI_EINJ_SET_ERROR_TYPE_WITH_ADDRESS &&\n\t\t entry->instruction == ACPI_EINJ_WRITE_REGISTER &&\n\t\t entry->register_region.space_id ==\n\t\t ACPI_ADR_SPACE_SYSTEM_MEMORY)\n\t\t\tpa_v5 = get_unaligned(&entry->register_region.address);\n\t\tentry++;\n\t}\n\tif (pa_v5) {\n\t\tstruct set_error_type_with_address *v5param;",
"\t\tv5param = acpi_os_map_iomem(pa_v5, sizeof(*v5param));\n\t\tif (v5param) {\n\t\t\tacpi5 = 1;\n\t\t\tcheck_vendor_extension(pa_v5, v5param);\n\t\t\treturn v5param;\n\t\t}\n\t}\n\tif (param_extension && pa_v4) {\n\t\tstruct einj_parameter *v4param;",
"\t\tv4param = acpi_os_map_iomem(pa_v4, sizeof(*v4param));\n\t\tif (!v4param)\n\t\t\treturn NULL;\n\t\tif (v4param->reserved1 || v4param->reserved2) {\n\t\t\tacpi_os_unmap_iomem(v4param, sizeof(*v4param));\n\t\t\treturn NULL;\n\t\t}\n\t\treturn v4param;\n\t}",
"\treturn NULL;\n}",
"/* do sanity check to trigger table */\nstatic int einj_check_trigger_header(struct acpi_einj_trigger *trigger_tab)\n{\n\tif (trigger_tab->header_size != sizeof(struct acpi_einj_trigger))\n\t\treturn -EINVAL;\n\tif (trigger_tab->table_size > PAGE_SIZE ||\n\t trigger_tab->table_size < trigger_tab->header_size)\n\t\treturn -EINVAL;\n\tif (trigger_tab->entry_count !=\n\t (trigger_tab->table_size - trigger_tab->header_size) /\n\t sizeof(struct acpi_einj_entry))\n\t\treturn -EINVAL;",
"\treturn 0;\n}",
"static struct acpi_generic_address *einj_get_trigger_parameter_region(\n\tstruct acpi_einj_trigger *trigger_tab, u64 param1, u64 param2)\n{\n\tint i;\n\tstruct acpi_whea_header *entry;",
"\tentry = (struct acpi_whea_header *)\n\t\t((char *)trigger_tab + sizeof(struct acpi_einj_trigger));\n\tfor (i = 0; i < trigger_tab->entry_count; i++) {\n\t\tif (entry->action == ACPI_EINJ_TRIGGER_ERROR &&\n\t\tentry->instruction == ACPI_EINJ_WRITE_REGISTER_VALUE &&\n\t\tentry->register_region.space_id ==\n\t\t\tACPI_ADR_SPACE_SYSTEM_MEMORY &&\n\t\t(entry->register_region.address & param2) == (param1 & param2))\n\t\t\treturn &entry->register_region;\n\t\tentry++;\n\t}",
"\treturn NULL;\n}\n/* Execute instructions in trigger error action table */\nstatic int __einj_error_trigger(u64 trigger_paddr, u32 type,\n\t\t\t\tu64 param1, u64 param2)\n{\n\tstruct acpi_einj_trigger *trigger_tab = NULL;\n\tstruct apei_exec_context trigger_ctx;\n\tstruct apei_resources trigger_resources;\n\tstruct acpi_whea_header *trigger_entry;\n\tstruct resource *r;\n\tu32 table_size;\n\tint rc = -EIO;\n\tstruct acpi_generic_address *trigger_param_region = NULL;",
"\tr = request_mem_region(trigger_paddr, sizeof(*trigger_tab),\n\t\t\t \"APEI EINJ Trigger Table\");\n\tif (!r) {\n\t\tpr_err(EINJ_PFX\n\t\"Can not request [mem %#010llx-%#010llx] for Trigger table\\n\",\n\t\t (unsigned long long)trigger_paddr,\n\t\t (unsigned long long)trigger_paddr +\n\t\t\t sizeof(*trigger_tab) - 1);\n\t\tgoto out;\n\t}\n\ttrigger_tab = ioremap_cache(trigger_paddr, sizeof(*trigger_tab));\n\tif (!trigger_tab) {\n\t\tpr_err(EINJ_PFX \"Failed to map trigger table!\\n\");\n\t\tgoto out_rel_header;\n\t}\n\trc = einj_check_trigger_header(trigger_tab);\n\tif (rc) {\n\t\tpr_warning(FW_BUG EINJ_PFX\n\t\t\t \"The trigger error action table is invalid\\n\");\n\t\tgoto out_rel_header;\n\t}",
"\t/* No action structures in the TRIGGER_ERROR table, nothing to do */\n\tif (!trigger_tab->entry_count)\n\t\tgoto out_rel_header;",
"\trc = -EIO;\n\ttable_size = trigger_tab->table_size;\n\tr = request_mem_region(trigger_paddr + sizeof(*trigger_tab),\n\t\t\t table_size - sizeof(*trigger_tab),\n\t\t\t \"APEI EINJ Trigger Table\");\n\tif (!r) {\n\t\tpr_err(EINJ_PFX\n\"Can not request [mem %#010llx-%#010llx] for Trigger Table Entry\\n\",\n\t\t (unsigned long long)trigger_paddr + sizeof(*trigger_tab),\n\t\t (unsigned long long)trigger_paddr + table_size - 1);\n\t\tgoto out_rel_header;\n\t}\n\tiounmap(trigger_tab);\n\ttrigger_tab = ioremap_cache(trigger_paddr, table_size);\n\tif (!trigger_tab) {\n\t\tpr_err(EINJ_PFX \"Failed to map trigger table!\\n\");\n\t\tgoto out_rel_entry;\n\t}\n\ttrigger_entry = (struct acpi_whea_header *)\n\t\t((char *)trigger_tab + sizeof(struct acpi_einj_trigger));\n\tapei_resources_init(&trigger_resources);\n\tapei_exec_ctx_init(&trigger_ctx, einj_ins_type,\n\t\t\t ARRAY_SIZE(einj_ins_type),\n\t\t\t trigger_entry, trigger_tab->entry_count);\n\trc = apei_exec_collect_resources(&trigger_ctx, &trigger_resources);\n\tif (rc)\n\t\tgoto out_fini;\n\trc = apei_resources_sub(&trigger_resources, &einj_resources);\n\tif (rc)\n\t\tgoto out_fini;\n\t/*\n\t * Some firmware will access target address specified in\n\t * param1 to trigger the error when injecting memory error.\n\t * This will cause resource conflict with regular memory. So\n\t * remove it from trigger table resources.\n\t */\n\tif ((param_extension || acpi5) && (type & MEM_ERROR_MASK) && param2) {\n\t\tstruct apei_resources addr_resources;\n\t\tapei_resources_init(&addr_resources);\n\t\ttrigger_param_region = einj_get_trigger_parameter_region(\n\t\t\ttrigger_tab, param1, param2);\n\t\tif (trigger_param_region) {\n\t\t\trc = apei_resources_add(&addr_resources,\n\t\t\t\ttrigger_param_region->address,\n\t\t\t\ttrigger_param_region->bit_width/8, true);\n\t\t\tif (rc)\n\t\t\t\tgoto out_fini;\n\t\t\trc = apei_resources_sub(&trigger_resources,\n\t\t\t\t\t&addr_resources);\n\t\t}\n\t\tapei_resources_fini(&addr_resources);\n\t\tif (rc)\n\t\t\tgoto out_fini;\n\t}\n\trc = apei_resources_request(&trigger_resources, \"APEI EINJ Trigger\");\n\tif (rc)\n\t\tgoto out_fini;\n\trc = apei_exec_pre_map_gars(&trigger_ctx);\n\tif (rc)\n\t\tgoto out_release;",
"\trc = apei_exec_run(&trigger_ctx, ACPI_EINJ_TRIGGER_ERROR);",
"\tapei_exec_post_unmap_gars(&trigger_ctx);\nout_release:\n\tapei_resources_release(&trigger_resources);\nout_fini:\n\tapei_resources_fini(&trigger_resources);\nout_rel_entry:\n\trelease_mem_region(trigger_paddr + sizeof(*trigger_tab),\n\t\t\t table_size - sizeof(*trigger_tab));\nout_rel_header:\n\trelease_mem_region(trigger_paddr, sizeof(*trigger_tab));\nout:\n\tif (trigger_tab)\n\t\tiounmap(trigger_tab);",
"\treturn rc;\n}",
"static int __einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,\n\t\t\t u64 param3, u64 param4)\n{\n\tstruct apei_exec_context ctx;\n\tu64 val, trigger_paddr, timeout = FIRMWARE_TIMEOUT;\n\tint rc;",
"\teinj_exec_ctx_init(&ctx);",
"\trc = apei_exec_run_optional(&ctx, ACPI_EINJ_BEGIN_OPERATION);\n\tif (rc)\n\t\treturn rc;\n\tapei_exec_ctx_set_input(&ctx, type);\n\tif (acpi5) {\n\t\tstruct set_error_type_with_address *v5param = einj_param;",
"\t\tv5param->type = type;\n\t\tif (type & ACPI5_VENDOR_BIT) {\n\t\t\tswitch (vendor_flags) {\n\t\t\tcase SETWA_FLAGS_APICID:\n\t\t\t\tv5param->apicid = param1;\n\t\t\t\tbreak;\n\t\t\tcase SETWA_FLAGS_MEM:\n\t\t\t\tv5param->memory_address = param1;\n\t\t\t\tv5param->memory_address_range = param2;\n\t\t\t\tbreak;\n\t\t\tcase SETWA_FLAGS_PCIE_SBDF:\n\t\t\t\tv5param->pcie_sbdf = param1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tv5param->flags = vendor_flags;\n\t\t} else if (flags) {\n\t\t\t\tv5param->flags = flags;\n\t\t\t\tv5param->memory_address = param1;\n\t\t\t\tv5param->memory_address_range = param2;\n\t\t\t\tv5param->apicid = param3;\n\t\t\t\tv5param->pcie_sbdf = param4;\n\t\t} else {\n\t\t\tswitch (type) {\n\t\t\tcase ACPI_EINJ_PROCESSOR_CORRECTABLE:\n\t\t\tcase ACPI_EINJ_PROCESSOR_UNCORRECTABLE:\n\t\t\tcase ACPI_EINJ_PROCESSOR_FATAL:\n\t\t\t\tv5param->apicid = param1;\n\t\t\t\tv5param->flags = SETWA_FLAGS_APICID;\n\t\t\t\tbreak;\n\t\t\tcase ACPI_EINJ_MEMORY_CORRECTABLE:\n\t\t\tcase ACPI_EINJ_MEMORY_UNCORRECTABLE:\n\t\t\tcase ACPI_EINJ_MEMORY_FATAL:\n\t\t\t\tv5param->memory_address = param1;\n\t\t\t\tv5param->memory_address_range = param2;\n\t\t\t\tv5param->flags = SETWA_FLAGS_MEM;\n\t\t\t\tbreak;\n\t\t\tcase ACPI_EINJ_PCIX_CORRECTABLE:\n\t\t\tcase ACPI_EINJ_PCIX_UNCORRECTABLE:\n\t\t\tcase ACPI_EINJ_PCIX_FATAL:\n\t\t\t\tv5param->pcie_sbdf = param1;\n\t\t\t\tv5param->flags = SETWA_FLAGS_PCIE_SBDF;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\trc = apei_exec_run(&ctx, ACPI_EINJ_SET_ERROR_TYPE);\n\t\tif (rc)\n\t\t\treturn rc;\n\t\tif (einj_param) {\n\t\t\tstruct einj_parameter *v4param = einj_param;\n\t\t\tv4param->param1 = param1;\n\t\t\tv4param->param2 = param2;\n\t\t}\n\t}\n\trc = apei_exec_run(&ctx, ACPI_EINJ_EXECUTE_OPERATION);\n\tif (rc)\n\t\treturn rc;\n\tfor (;;) {\n\t\trc = apei_exec_run(&ctx, ACPI_EINJ_CHECK_BUSY_STATUS);\n\t\tif (rc)\n\t\t\treturn rc;\n\t\tval = apei_exec_ctx_get_output(&ctx);\n\t\tif (!(val & EINJ_OP_BUSY))\n\t\t\tbreak;\n\t\tif (einj_timedout(&timeout))\n\t\t\treturn -EIO;\n\t}\n\trc = apei_exec_run(&ctx, ACPI_EINJ_GET_COMMAND_STATUS);\n\tif (rc)\n\t\treturn rc;\n\tval = apei_exec_ctx_get_output(&ctx);\n\tif (val != EINJ_STATUS_SUCCESS)\n\t\treturn -EBUSY;",
"\trc = apei_exec_run(&ctx, ACPI_EINJ_GET_TRIGGER_TABLE);\n\tif (rc)\n\t\treturn rc;\n\ttrigger_paddr = apei_exec_ctx_get_output(&ctx);\n\tif (notrigger == 0) {\n\t\trc = __einj_error_trigger(trigger_paddr, type, param1, param2);\n\t\tif (rc)\n\t\t\treturn rc;\n\t}\n\trc = apei_exec_run_optional(&ctx, ACPI_EINJ_END_OPERATION);",
"\treturn rc;\n}",
"/* Inject the specified hardware error */\nstatic int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,\n\t\t\t u64 param3, u64 param4)\n{\n\tint rc;\n\tu64 base_addr, size;\n",
"",
"\t/* If user manually set \"flags\", make sure it is legal */\n\tif (flags && (flags &\n\t\t~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))\n\t\treturn -EINVAL;",
"\t/*\n\t * We need extra sanity checks for memory errors.\n\t * Other types leap directly to injection.\n\t */",
"\t/* ensure param1/param2 existed */\n\tif (!(param_extension || acpi5))\n\t\tgoto inject;",
"\t/* ensure injection is memory related */\n\tif (type & ACPI5_VENDOR_BIT) {\n\t\tif (vendor_flags != SETWA_FLAGS_MEM)\n\t\t\tgoto inject;\n\t} else if (!(type & MEM_ERROR_MASK) && !(flags & SETWA_FLAGS_MEM))\n\t\tgoto inject;",
"\t/*\n\t * Disallow crazy address masks that give BIOS leeway to pick\n\t * injection address almost anywhere. Insist on page or\n\t * better granularity and that target address is normal RAM or\n\t * NVDIMM.\n\t */\n\tbase_addr = param1 & param2;\n\tsize = ~param2 + 1;",
"\tif (((param2 & PAGE_MASK) != PAGE_MASK) ||\n\t ((region_intersects(base_addr, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE)\n\t\t\t\t!= REGION_INTERSECTS) &&\n\t (region_intersects(base_addr, size, IORESOURCE_MEM, IORES_DESC_PERSISTENT_MEMORY)\n\t\t\t\t!= REGION_INTERSECTS)))\n\t\treturn -EINVAL;",
"inject:\n\tmutex_lock(&einj_mutex);\n\trc = __einj_error_inject(type, flags, param1, param2, param3, param4);\n\tmutex_unlock(&einj_mutex);",
"\treturn rc;\n}",
"static u32 error_type;\nstatic u32 error_flags;\nstatic u64 error_param1;\nstatic u64 error_param2;\nstatic u64 error_param3;\nstatic u64 error_param4;\nstatic struct dentry *einj_debug_dir;",
"static int available_error_type_show(struct seq_file *m, void *v)\n{\n\tint rc;\n\tu32 available_error_type = 0;",
"\trc = einj_get_available_error_type(&available_error_type);\n\tif (rc)\n\t\treturn rc;\n\tif (available_error_type & 0x0001)\n\t\tseq_printf(m, \"0x00000001\\tProcessor Correctable\\n\");\n\tif (available_error_type & 0x0002)\n\t\tseq_printf(m, \"0x00000002\\tProcessor Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0004)\n\t\tseq_printf(m, \"0x00000004\\tProcessor Uncorrectable fatal\\n\");\n\tif (available_error_type & 0x0008)\n\t\tseq_printf(m, \"0x00000008\\tMemory Correctable\\n\");\n\tif (available_error_type & 0x0010)\n\t\tseq_printf(m, \"0x00000010\\tMemory Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0020)\n\t\tseq_printf(m, \"0x00000020\\tMemory Uncorrectable fatal\\n\");\n\tif (available_error_type & 0x0040)\n\t\tseq_printf(m, \"0x00000040\\tPCI Express Correctable\\n\");\n\tif (available_error_type & 0x0080)\n\t\tseq_printf(m, \"0x00000080\\tPCI Express Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0100)\n\t\tseq_printf(m, \"0x00000100\\tPCI Express Uncorrectable fatal\\n\");\n\tif (available_error_type & 0x0200)\n\t\tseq_printf(m, \"0x00000200\\tPlatform Correctable\\n\");\n\tif (available_error_type & 0x0400)\n\t\tseq_printf(m, \"0x00000400\\tPlatform Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0800)\n\t\tseq_printf(m, \"0x00000800\\tPlatform Uncorrectable fatal\\n\");",
"\treturn 0;\n}",
"static int available_error_type_open(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, available_error_type_show, NULL);\n}",
"static const struct file_operations available_error_type_fops = {\n\t.open\t\t= available_error_type_open,\n\t.read\t\t= seq_read,\n\t.llseek\t\t= seq_lseek,\n\t.release\t= single_release,\n};",
"static int error_type_get(void *data, u64 *val)\n{\n\t*val = error_type;",
"\treturn 0;\n}",
"static int error_type_set(void *data, u64 val)\n{\n\tint rc;\n\tu32 available_error_type = 0;\n\tu32 tval, vendor;",
"\t/*\n\t * Vendor defined types have 0x80000000 bit set, and\n\t * are not enumerated by ACPI_EINJ_GET_ERROR_TYPE\n\t */\n\tvendor = val & ACPI5_VENDOR_BIT;\n\ttval = val & 0x7fffffff;",
"\t/* Only one error type can be specified */\n\tif (tval & (tval - 1))\n\t\treturn -EINVAL;\n\tif (!vendor) {\n\t\trc = einj_get_available_error_type(&available_error_type);\n\t\tif (rc)\n\t\t\treturn rc;\n\t\tif (!(val & available_error_type))\n\t\t\treturn -EINVAL;\n\t}\n\terror_type = val;",
"\treturn 0;\n}",
"DEFINE_SIMPLE_ATTRIBUTE(error_type_fops, error_type_get,\n\t\t\terror_type_set, \"0x%llx\\n\");",
"static int error_inject_set(void *data, u64 val)\n{\n\tif (!error_type)\n\t\treturn -EINVAL;",
"\treturn einj_error_inject(error_type, error_flags, error_param1, error_param2,\n\t\terror_param3, error_param4);\n}",
"DEFINE_SIMPLE_ATTRIBUTE(error_inject_fops, NULL,\n\t\t\terror_inject_set, \"%llu\\n\");",
"static int einj_check_table(struct acpi_table_einj *einj_tab)\n{\n\tif ((einj_tab->header_length !=\n\t (sizeof(struct acpi_table_einj) - sizeof(einj_tab->header)))\n\t && (einj_tab->header_length != sizeof(struct acpi_table_einj)))\n\t\treturn -EINVAL;\n\tif (einj_tab->header.length < sizeof(struct acpi_table_einj))\n\t\treturn -EINVAL;\n\tif (einj_tab->entries !=\n\t (einj_tab->header.length - sizeof(struct acpi_table_einj)) /\n\t sizeof(struct acpi_einj_entry))\n\t\treturn -EINVAL;",
"\treturn 0;\n}",
"static int __init einj_init(void)\n{\n\tint rc;\n\tacpi_status status;\n\tstruct dentry *fentry;\n\tstruct apei_exec_context ctx;",
"\tif (acpi_disabled)\n\t\treturn -ENODEV;",
"\tstatus = acpi_get_table(ACPI_SIG_EINJ, 0,\n\t\t\t\t(struct acpi_table_header **)&einj_tab);\n\tif (status == AE_NOT_FOUND)\n\t\treturn -ENODEV;\n\telse if (ACPI_FAILURE(status)) {\n\t\tconst char *msg = acpi_format_exception(status);\n\t\tpr_err(EINJ_PFX \"Failed to get table, %s\\n\", msg);\n\t\treturn -EINVAL;\n\t}",
"\trc = einj_check_table(einj_tab);\n\tif (rc) {\n\t\tpr_warning(FW_BUG EINJ_PFX \"EINJ table is invalid\\n\");\n\t\treturn -EINVAL;\n\t}",
"\trc = -ENOMEM;\n\teinj_debug_dir = debugfs_create_dir(\"einj\", apei_get_debugfs_dir());\n\tif (!einj_debug_dir)\n\t\tgoto err_cleanup;\n\tfentry = debugfs_create_file(\"available_error_type\", S_IRUSR,\n\t\t\t\t einj_debug_dir, NULL,\n\t\t\t\t &available_error_type_fops);\n\tif (!fentry)\n\t\tgoto err_cleanup;\n\tfentry = debugfs_create_file(\"error_type\", S_IRUSR | S_IWUSR,\n\t\t\t\t einj_debug_dir, NULL, &error_type_fops);\n\tif (!fentry)\n\t\tgoto err_cleanup;\n\tfentry = debugfs_create_file(\"error_inject\", S_IWUSR,\n\t\t\t\t einj_debug_dir, NULL, &error_inject_fops);\n\tif (!fentry)\n\t\tgoto err_cleanup;",
"\tapei_resources_init(&einj_resources);\n\teinj_exec_ctx_init(&ctx);\n\trc = apei_exec_collect_resources(&ctx, &einj_resources);\n\tif (rc)\n\t\tgoto err_fini;\n\trc = apei_resources_request(&einj_resources, \"APEI EINJ\");\n\tif (rc)\n\t\tgoto err_fini;\n\trc = apei_exec_pre_map_gars(&ctx);\n\tif (rc)\n\t\tgoto err_release;",
"\trc = -ENOMEM;\n\teinj_param = einj_get_parameter_address();\n\tif ((param_extension || acpi5) && einj_param) {\n\t\tfentry = debugfs_create_x32(\"flags\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_flags);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param1\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param1);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param2\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param2);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param3\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param3);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param4\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param4);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;",
"\t\tfentry = debugfs_create_x32(\"notrigger\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, ¬rigger);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t}",
"\tif (vendor_dev[0]) {\n\t\tvendor_blob.data = vendor_dev;\n\t\tvendor_blob.size = strlen(vendor_dev);\n\t\tfentry = debugfs_create_blob(\"vendor\", S_IRUSR,\n\t\t\t\t\t einj_debug_dir, &vendor_blob);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x32(\"vendor_flags\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &vendor_flags);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t}",
"\tpr_info(EINJ_PFX \"Error INJection is initialized.\\n\");",
"\treturn 0;",
"err_unmap:\n\tif (einj_param) {\n\t\tacpi_size size = (acpi5) ?\n\t\t\tsizeof(struct set_error_type_with_address) :\n\t\t\tsizeof(struct einj_parameter);",
"\t\tacpi_os_unmap_iomem(einj_param, size);\n\t}\n\tapei_exec_post_unmap_gars(&ctx);\nerr_release:\n\tapei_resources_release(&einj_resources);\nerr_fini:\n\tapei_resources_fini(&einj_resources);\nerr_cleanup:\n\tdebugfs_remove_recursive(einj_debug_dir);",
"\treturn rc;\n}",
"static void __exit einj_exit(void)\n{\n\tstruct apei_exec_context ctx;",
"\tif (einj_param) {\n\t\tacpi_size size = (acpi5) ?\n\t\t\tsizeof(struct set_error_type_with_address) :\n\t\t\tsizeof(struct einj_parameter);",
"\t\tacpi_os_unmap_iomem(einj_param, size);\n\t}\n\teinj_exec_ctx_init(&ctx);\n\tapei_exec_post_unmap_gars(&ctx);\n\tapei_resources_release(&einj_resources);\n\tapei_resources_fini(&einj_resources);\n\tdebugfs_remove_recursive(einj_debug_dir);\n}",
"module_init(einj_init);\nmodule_exit(einj_exit);",
"MODULE_AUTHOR(\"Huang Ying\");\nMODULE_DESCRIPTION(\"APEI Error INJection support\");\nMODULE_LICENSE(\"GPL\");"
] |
[
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,
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": [523], "buggy_code_start_loc": [31], "filenames": ["drivers/acpi/apei/einj.c"], "fixing_code_end_loc": [528], "fixing_code_start_loc": [32], "message": "The einj_error_inject function in drivers/acpi/apei/einj.c in the Linux kernel allows local users to simulate hardware errors and consequently cause a denial of service by leveraging failure to disable APEI error injection through EINJ when securelevel is set.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:-:*:*:*:*:*:*:*", "matchCriteriaId": "703AF700-7A70-47E2-BC3A-7FD03B3CA9C1", "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:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "142AD0DD-4CF3-4D74-9442-459CE3347E3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The einj_error_inject function in drivers/acpi/apei/einj.c in the Linux kernel allows local users to simulate hardware errors and consequently cause a denial of service by leveraging failure to disable APEI error injection through EINJ when securelevel is set."}, {"lang": "es", "value": "La funci\u00f3n einj_error_inject en drivers/acpi/apei/einj.c en el kernel de Linux permite que usuarios locales simulen errores de hardware y, consecuentemente, provoquen una denegaci\u00f3n de servicio (DoS) aprovechando el error a la hora de deshabilitar la inyecci\u00f3n de errores APEI mediante EINJ cuando est\u00e1 establecido securelevel."}], "evaluatorComment": null, "id": "CVE-2016-3695", "lastModified": "2018-01-10T16:44:01.997", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/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-12-29T15:29:00.580", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/102327"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1322755"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/mjg59/linux/commit/d7a6be58edc01b1c66ecd8fcc91236bfbce0a420"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/mjg59/linux/commit/d7a6be58edc01b1c66ecd8fcc91236bfbce0a420"}, "type": "CWE-74"}
| 314
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/*\n * APEI Error INJection support\n *\n * EINJ provides a hardware error injection mechanism, this is useful\n * for debugging and testing of other APEI and RAS features.\n *\n * For more information about EINJ, please refer to ACPI Specification\n * version 4.0, section 17.5.\n *\n * Copyright 2009-2010 Intel Corp.\n * Author: Huang Ying <ying.huang@intel.com>\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 version\n * 2 as published by the Free Software Foundation.\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 */",
"#include <linux/kernel.h>\n#include <linux/module.h>\n#include <linux/init.h>\n#include <linux/io.h>\n#include <linux/debugfs.h>\n#include <linux/seq_file.h>\n#include <linux/nmi.h>\n#include <linux/delay.h>\n#include <linux/mm.h>",
"#include <linux/security.h>",
"#include <asm/unaligned.h>",
"#include \"apei-internal.h\"",
"#define EINJ_PFX \"EINJ: \"",
"#define SPIN_UNIT\t\t100\t\t\t/* 100ns */\n/* Firmware should respond within 1 milliseconds */\n#define FIRMWARE_TIMEOUT\t(1 * NSEC_PER_MSEC)\n#define ACPI5_VENDOR_BIT\tBIT(31)\n#define MEM_ERROR_MASK\t\t(ACPI_EINJ_MEMORY_CORRECTABLE | \\\n\t\t\t\tACPI_EINJ_MEMORY_UNCORRECTABLE | \\\n\t\t\t\tACPI_EINJ_MEMORY_FATAL)",
"/*\n * ACPI version 5 provides a SET_ERROR_TYPE_WITH_ADDRESS action.\n */\nstatic int acpi5;",
"struct set_error_type_with_address {\n\tu32\ttype;\n\tu32\tvendor_extension;\n\tu32\tflags;\n\tu32\tapicid;\n\tu64\tmemory_address;\n\tu64\tmemory_address_range;\n\tu32\tpcie_sbdf;\n};\nenum {\n\tSETWA_FLAGS_APICID = 1,\n\tSETWA_FLAGS_MEM = 2,\n\tSETWA_FLAGS_PCIE_SBDF = 4,\n};",
"/*\n * Vendor extensions for platform specific operations\n */\nstruct vendor_error_type_extension {\n\tu32\tlength;\n\tu32\tpcie_sbdf;\n\tu16\tvendor_id;\n\tu16\tdevice_id;\n\tu8\trev_id;\n\tu8\treserved[3];\n};",
"static u32 notrigger;",
"static u32 vendor_flags;\nstatic struct debugfs_blob_wrapper vendor_blob;\nstatic char vendor_dev[64];",
"/*\n * Some BIOSes allow parameters to the SET_ERROR_TYPE entries in the\n * EINJ table through an unpublished extension. Use with caution as\n * most will ignore the parameter and make their own choice of address\n * for error injection. This extension is used only if\n * param_extension module parameter is specified.\n */\nstruct einj_parameter {\n\tu64 type;\n\tu64 reserved1;\n\tu64 reserved2;\n\tu64 param1;\n\tu64 param2;\n};",
"#define EINJ_OP_BUSY\t\t\t0x1\n#define EINJ_STATUS_SUCCESS\t\t0x0\n#define EINJ_STATUS_FAIL\t\t0x1\n#define EINJ_STATUS_INVAL\t\t0x2",
"#define EINJ_TAB_ENTRY(tab)\t\t\t\t\t\t\\\n\t((struct acpi_whea_header *)((char *)(tab) +\t\t\t\\\n\t\t\t\t sizeof(struct acpi_table_einj)))",
"static bool param_extension;\nmodule_param(param_extension, bool, 0);",
"static struct acpi_table_einj *einj_tab;",
"static struct apei_resources einj_resources;",
"static struct apei_exec_ins_type einj_ins_type[] = {\n\t[ACPI_EINJ_READ_REGISTER] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_read_register,\n\t},\n\t[ACPI_EINJ_READ_REGISTER_VALUE] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_read_register_value,\n\t},\n\t[ACPI_EINJ_WRITE_REGISTER] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_write_register,\n\t},\n\t[ACPI_EINJ_WRITE_REGISTER_VALUE] = {\n\t\t.flags = APEI_EXEC_INS_ACCESS_REGISTER,\n\t\t.run = apei_exec_write_register_value,\n\t},\n\t[ACPI_EINJ_NOOP] = {\n\t\t.flags = 0,\n\t\t.run = apei_exec_noop,\n\t},\n};",
"/*\n * Prevent EINJ interpreter to run simultaneously, because the\n * corresponding firmware implementation may not work properly when\n * invoked simultaneously.\n */\nstatic DEFINE_MUTEX(einj_mutex);",
"static void *einj_param;",
"static void einj_exec_ctx_init(struct apei_exec_context *ctx)\n{\n\tapei_exec_ctx_init(ctx, einj_ins_type, ARRAY_SIZE(einj_ins_type),\n\t\t\t EINJ_TAB_ENTRY(einj_tab), einj_tab->entries);\n}",
"static int __einj_get_available_error_type(u32 *type)\n{\n\tstruct apei_exec_context ctx;\n\tint rc;",
"\teinj_exec_ctx_init(&ctx);\n\trc = apei_exec_run(&ctx, ACPI_EINJ_GET_ERROR_TYPE);\n\tif (rc)\n\t\treturn rc;\n\t*type = apei_exec_ctx_get_output(&ctx);",
"\treturn 0;\n}",
"/* Get error injection capabilities of the platform */\nstatic int einj_get_available_error_type(u32 *type)\n{\n\tint rc;",
"\tmutex_lock(&einj_mutex);\n\trc = __einj_get_available_error_type(type);\n\tmutex_unlock(&einj_mutex);",
"\treturn rc;\n}",
"static int einj_timedout(u64 *t)\n{\n\tif ((s64)*t < SPIN_UNIT) {\n\t\tpr_warning(FW_WARN EINJ_PFX\n\t\t\t \"Firmware does not respond in time\\n\");\n\t\treturn 1;\n\t}\n\t*t -= SPIN_UNIT;\n\tndelay(SPIN_UNIT);\n\ttouch_nmi_watchdog();\n\treturn 0;\n}",
"static void check_vendor_extension(u64 paddr,\n\t\t\t\t struct set_error_type_with_address *v5param)\n{\n\tint\toffset = v5param->vendor_extension;\n\tstruct\tvendor_error_type_extension *v;\n\tu32\tsbdf;",
"\tif (!offset)\n\t\treturn;\n\tv = acpi_os_map_iomem(paddr + offset, sizeof(*v));\n\tif (!v)\n\t\treturn;\n\tsbdf = v->pcie_sbdf;\n\tsprintf(vendor_dev, \"%x:%x:%x.%x vendor_id=%x device_id=%x rev_id=%x\\n\",\n\t\tsbdf >> 24, (sbdf >> 16) & 0xff,\n\t\t(sbdf >> 11) & 0x1f, (sbdf >> 8) & 0x7,\n\t\t v->vendor_id, v->device_id, v->rev_id);\n\tacpi_os_unmap_iomem(v, sizeof(*v));\n}",
"static void *einj_get_parameter_address(void)\n{\n\tint i;\n\tu64 pa_v4 = 0, pa_v5 = 0;\n\tstruct acpi_whea_header *entry;",
"\tentry = EINJ_TAB_ENTRY(einj_tab);\n\tfor (i = 0; i < einj_tab->entries; i++) {\n\t\tif (entry->action == ACPI_EINJ_SET_ERROR_TYPE &&\n\t\t entry->instruction == ACPI_EINJ_WRITE_REGISTER &&\n\t\t entry->register_region.space_id ==\n\t\t ACPI_ADR_SPACE_SYSTEM_MEMORY)\n\t\t\tpa_v4 = get_unaligned(&entry->register_region.address);\n\t\tif (entry->action == ACPI_EINJ_SET_ERROR_TYPE_WITH_ADDRESS &&\n\t\t entry->instruction == ACPI_EINJ_WRITE_REGISTER &&\n\t\t entry->register_region.space_id ==\n\t\t ACPI_ADR_SPACE_SYSTEM_MEMORY)\n\t\t\tpa_v5 = get_unaligned(&entry->register_region.address);\n\t\tentry++;\n\t}\n\tif (pa_v5) {\n\t\tstruct set_error_type_with_address *v5param;",
"\t\tv5param = acpi_os_map_iomem(pa_v5, sizeof(*v5param));\n\t\tif (v5param) {\n\t\t\tacpi5 = 1;\n\t\t\tcheck_vendor_extension(pa_v5, v5param);\n\t\t\treturn v5param;\n\t\t}\n\t}\n\tif (param_extension && pa_v4) {\n\t\tstruct einj_parameter *v4param;",
"\t\tv4param = acpi_os_map_iomem(pa_v4, sizeof(*v4param));\n\t\tif (!v4param)\n\t\t\treturn NULL;\n\t\tif (v4param->reserved1 || v4param->reserved2) {\n\t\t\tacpi_os_unmap_iomem(v4param, sizeof(*v4param));\n\t\t\treturn NULL;\n\t\t}\n\t\treturn v4param;\n\t}",
"\treturn NULL;\n}",
"/* do sanity check to trigger table */\nstatic int einj_check_trigger_header(struct acpi_einj_trigger *trigger_tab)\n{\n\tif (trigger_tab->header_size != sizeof(struct acpi_einj_trigger))\n\t\treturn -EINVAL;\n\tif (trigger_tab->table_size > PAGE_SIZE ||\n\t trigger_tab->table_size < trigger_tab->header_size)\n\t\treturn -EINVAL;\n\tif (trigger_tab->entry_count !=\n\t (trigger_tab->table_size - trigger_tab->header_size) /\n\t sizeof(struct acpi_einj_entry))\n\t\treturn -EINVAL;",
"\treturn 0;\n}",
"static struct acpi_generic_address *einj_get_trigger_parameter_region(\n\tstruct acpi_einj_trigger *trigger_tab, u64 param1, u64 param2)\n{\n\tint i;\n\tstruct acpi_whea_header *entry;",
"\tentry = (struct acpi_whea_header *)\n\t\t((char *)trigger_tab + sizeof(struct acpi_einj_trigger));\n\tfor (i = 0; i < trigger_tab->entry_count; i++) {\n\t\tif (entry->action == ACPI_EINJ_TRIGGER_ERROR &&\n\t\tentry->instruction == ACPI_EINJ_WRITE_REGISTER_VALUE &&\n\t\tentry->register_region.space_id ==\n\t\t\tACPI_ADR_SPACE_SYSTEM_MEMORY &&\n\t\t(entry->register_region.address & param2) == (param1 & param2))\n\t\t\treturn &entry->register_region;\n\t\tentry++;\n\t}",
"\treturn NULL;\n}\n/* Execute instructions in trigger error action table */\nstatic int __einj_error_trigger(u64 trigger_paddr, u32 type,\n\t\t\t\tu64 param1, u64 param2)\n{\n\tstruct acpi_einj_trigger *trigger_tab = NULL;\n\tstruct apei_exec_context trigger_ctx;\n\tstruct apei_resources trigger_resources;\n\tstruct acpi_whea_header *trigger_entry;\n\tstruct resource *r;\n\tu32 table_size;\n\tint rc = -EIO;\n\tstruct acpi_generic_address *trigger_param_region = NULL;",
"\tr = request_mem_region(trigger_paddr, sizeof(*trigger_tab),\n\t\t\t \"APEI EINJ Trigger Table\");\n\tif (!r) {\n\t\tpr_err(EINJ_PFX\n\t\"Can not request [mem %#010llx-%#010llx] for Trigger table\\n\",\n\t\t (unsigned long long)trigger_paddr,\n\t\t (unsigned long long)trigger_paddr +\n\t\t\t sizeof(*trigger_tab) - 1);\n\t\tgoto out;\n\t}\n\ttrigger_tab = ioremap_cache(trigger_paddr, sizeof(*trigger_tab));\n\tif (!trigger_tab) {\n\t\tpr_err(EINJ_PFX \"Failed to map trigger table!\\n\");\n\t\tgoto out_rel_header;\n\t}\n\trc = einj_check_trigger_header(trigger_tab);\n\tif (rc) {\n\t\tpr_warning(FW_BUG EINJ_PFX\n\t\t\t \"The trigger error action table is invalid\\n\");\n\t\tgoto out_rel_header;\n\t}",
"\t/* No action structures in the TRIGGER_ERROR table, nothing to do */\n\tif (!trigger_tab->entry_count)\n\t\tgoto out_rel_header;",
"\trc = -EIO;\n\ttable_size = trigger_tab->table_size;\n\tr = request_mem_region(trigger_paddr + sizeof(*trigger_tab),\n\t\t\t table_size - sizeof(*trigger_tab),\n\t\t\t \"APEI EINJ Trigger Table\");\n\tif (!r) {\n\t\tpr_err(EINJ_PFX\n\"Can not request [mem %#010llx-%#010llx] for Trigger Table Entry\\n\",\n\t\t (unsigned long long)trigger_paddr + sizeof(*trigger_tab),\n\t\t (unsigned long long)trigger_paddr + table_size - 1);\n\t\tgoto out_rel_header;\n\t}\n\tiounmap(trigger_tab);\n\ttrigger_tab = ioremap_cache(trigger_paddr, table_size);\n\tif (!trigger_tab) {\n\t\tpr_err(EINJ_PFX \"Failed to map trigger table!\\n\");\n\t\tgoto out_rel_entry;\n\t}\n\ttrigger_entry = (struct acpi_whea_header *)\n\t\t((char *)trigger_tab + sizeof(struct acpi_einj_trigger));\n\tapei_resources_init(&trigger_resources);\n\tapei_exec_ctx_init(&trigger_ctx, einj_ins_type,\n\t\t\t ARRAY_SIZE(einj_ins_type),\n\t\t\t trigger_entry, trigger_tab->entry_count);\n\trc = apei_exec_collect_resources(&trigger_ctx, &trigger_resources);\n\tif (rc)\n\t\tgoto out_fini;\n\trc = apei_resources_sub(&trigger_resources, &einj_resources);\n\tif (rc)\n\t\tgoto out_fini;\n\t/*\n\t * Some firmware will access target address specified in\n\t * param1 to trigger the error when injecting memory error.\n\t * This will cause resource conflict with regular memory. So\n\t * remove it from trigger table resources.\n\t */\n\tif ((param_extension || acpi5) && (type & MEM_ERROR_MASK) && param2) {\n\t\tstruct apei_resources addr_resources;\n\t\tapei_resources_init(&addr_resources);\n\t\ttrigger_param_region = einj_get_trigger_parameter_region(\n\t\t\ttrigger_tab, param1, param2);\n\t\tif (trigger_param_region) {\n\t\t\trc = apei_resources_add(&addr_resources,\n\t\t\t\ttrigger_param_region->address,\n\t\t\t\ttrigger_param_region->bit_width/8, true);\n\t\t\tif (rc)\n\t\t\t\tgoto out_fini;\n\t\t\trc = apei_resources_sub(&trigger_resources,\n\t\t\t\t\t&addr_resources);\n\t\t}\n\t\tapei_resources_fini(&addr_resources);\n\t\tif (rc)\n\t\t\tgoto out_fini;\n\t}\n\trc = apei_resources_request(&trigger_resources, \"APEI EINJ Trigger\");\n\tif (rc)\n\t\tgoto out_fini;\n\trc = apei_exec_pre_map_gars(&trigger_ctx);\n\tif (rc)\n\t\tgoto out_release;",
"\trc = apei_exec_run(&trigger_ctx, ACPI_EINJ_TRIGGER_ERROR);",
"\tapei_exec_post_unmap_gars(&trigger_ctx);\nout_release:\n\tapei_resources_release(&trigger_resources);\nout_fini:\n\tapei_resources_fini(&trigger_resources);\nout_rel_entry:\n\trelease_mem_region(trigger_paddr + sizeof(*trigger_tab),\n\t\t\t table_size - sizeof(*trigger_tab));\nout_rel_header:\n\trelease_mem_region(trigger_paddr, sizeof(*trigger_tab));\nout:\n\tif (trigger_tab)\n\t\tiounmap(trigger_tab);",
"\treturn rc;\n}",
"static int __einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,\n\t\t\t u64 param3, u64 param4)\n{\n\tstruct apei_exec_context ctx;\n\tu64 val, trigger_paddr, timeout = FIRMWARE_TIMEOUT;\n\tint rc;",
"\teinj_exec_ctx_init(&ctx);",
"\trc = apei_exec_run_optional(&ctx, ACPI_EINJ_BEGIN_OPERATION);\n\tif (rc)\n\t\treturn rc;\n\tapei_exec_ctx_set_input(&ctx, type);\n\tif (acpi5) {\n\t\tstruct set_error_type_with_address *v5param = einj_param;",
"\t\tv5param->type = type;\n\t\tif (type & ACPI5_VENDOR_BIT) {\n\t\t\tswitch (vendor_flags) {\n\t\t\tcase SETWA_FLAGS_APICID:\n\t\t\t\tv5param->apicid = param1;\n\t\t\t\tbreak;\n\t\t\tcase SETWA_FLAGS_MEM:\n\t\t\t\tv5param->memory_address = param1;\n\t\t\t\tv5param->memory_address_range = param2;\n\t\t\t\tbreak;\n\t\t\tcase SETWA_FLAGS_PCIE_SBDF:\n\t\t\t\tv5param->pcie_sbdf = param1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tv5param->flags = vendor_flags;\n\t\t} else if (flags) {\n\t\t\t\tv5param->flags = flags;\n\t\t\t\tv5param->memory_address = param1;\n\t\t\t\tv5param->memory_address_range = param2;\n\t\t\t\tv5param->apicid = param3;\n\t\t\t\tv5param->pcie_sbdf = param4;\n\t\t} else {\n\t\t\tswitch (type) {\n\t\t\tcase ACPI_EINJ_PROCESSOR_CORRECTABLE:\n\t\t\tcase ACPI_EINJ_PROCESSOR_UNCORRECTABLE:\n\t\t\tcase ACPI_EINJ_PROCESSOR_FATAL:\n\t\t\t\tv5param->apicid = param1;\n\t\t\t\tv5param->flags = SETWA_FLAGS_APICID;\n\t\t\t\tbreak;\n\t\t\tcase ACPI_EINJ_MEMORY_CORRECTABLE:\n\t\t\tcase ACPI_EINJ_MEMORY_UNCORRECTABLE:\n\t\t\tcase ACPI_EINJ_MEMORY_FATAL:\n\t\t\t\tv5param->memory_address = param1;\n\t\t\t\tv5param->memory_address_range = param2;\n\t\t\t\tv5param->flags = SETWA_FLAGS_MEM;\n\t\t\t\tbreak;\n\t\t\tcase ACPI_EINJ_PCIX_CORRECTABLE:\n\t\t\tcase ACPI_EINJ_PCIX_UNCORRECTABLE:\n\t\t\tcase ACPI_EINJ_PCIX_FATAL:\n\t\t\t\tv5param->pcie_sbdf = param1;\n\t\t\t\tv5param->flags = SETWA_FLAGS_PCIE_SBDF;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else {\n\t\trc = apei_exec_run(&ctx, ACPI_EINJ_SET_ERROR_TYPE);\n\t\tif (rc)\n\t\t\treturn rc;\n\t\tif (einj_param) {\n\t\t\tstruct einj_parameter *v4param = einj_param;\n\t\t\tv4param->param1 = param1;\n\t\t\tv4param->param2 = param2;\n\t\t}\n\t}\n\trc = apei_exec_run(&ctx, ACPI_EINJ_EXECUTE_OPERATION);\n\tif (rc)\n\t\treturn rc;\n\tfor (;;) {\n\t\trc = apei_exec_run(&ctx, ACPI_EINJ_CHECK_BUSY_STATUS);\n\t\tif (rc)\n\t\t\treturn rc;\n\t\tval = apei_exec_ctx_get_output(&ctx);\n\t\tif (!(val & EINJ_OP_BUSY))\n\t\t\tbreak;\n\t\tif (einj_timedout(&timeout))\n\t\t\treturn -EIO;\n\t}\n\trc = apei_exec_run(&ctx, ACPI_EINJ_GET_COMMAND_STATUS);\n\tif (rc)\n\t\treturn rc;\n\tval = apei_exec_ctx_get_output(&ctx);\n\tif (val != EINJ_STATUS_SUCCESS)\n\t\treturn -EBUSY;",
"\trc = apei_exec_run(&ctx, ACPI_EINJ_GET_TRIGGER_TABLE);\n\tif (rc)\n\t\treturn rc;\n\ttrigger_paddr = apei_exec_ctx_get_output(&ctx);\n\tif (notrigger == 0) {\n\t\trc = __einj_error_trigger(trigger_paddr, type, param1, param2);\n\t\tif (rc)\n\t\t\treturn rc;\n\t}\n\trc = apei_exec_run_optional(&ctx, ACPI_EINJ_END_OPERATION);",
"\treturn rc;\n}",
"/* Inject the specified hardware error */\nstatic int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,\n\t\t\t u64 param3, u64 param4)\n{\n\tint rc;\n\tu64 base_addr, size;\n",
"\tif (get_securelevel() > 0)\n\t\treturn -EPERM;\n",
"\t/* If user manually set \"flags\", make sure it is legal */\n\tif (flags && (flags &\n\t\t~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))\n\t\treturn -EINVAL;",
"\t/*\n\t * We need extra sanity checks for memory errors.\n\t * Other types leap directly to injection.\n\t */",
"\t/* ensure param1/param2 existed */\n\tif (!(param_extension || acpi5))\n\t\tgoto inject;",
"\t/* ensure injection is memory related */\n\tif (type & ACPI5_VENDOR_BIT) {\n\t\tif (vendor_flags != SETWA_FLAGS_MEM)\n\t\t\tgoto inject;\n\t} else if (!(type & MEM_ERROR_MASK) && !(flags & SETWA_FLAGS_MEM))\n\t\tgoto inject;",
"\t/*\n\t * Disallow crazy address masks that give BIOS leeway to pick\n\t * injection address almost anywhere. Insist on page or\n\t * better granularity and that target address is normal RAM or\n\t * NVDIMM.\n\t */\n\tbase_addr = param1 & param2;\n\tsize = ~param2 + 1;",
"\tif (((param2 & PAGE_MASK) != PAGE_MASK) ||\n\t ((region_intersects(base_addr, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE)\n\t\t\t\t!= REGION_INTERSECTS) &&\n\t (region_intersects(base_addr, size, IORESOURCE_MEM, IORES_DESC_PERSISTENT_MEMORY)\n\t\t\t\t!= REGION_INTERSECTS)))\n\t\treturn -EINVAL;",
"inject:\n\tmutex_lock(&einj_mutex);\n\trc = __einj_error_inject(type, flags, param1, param2, param3, param4);\n\tmutex_unlock(&einj_mutex);",
"\treturn rc;\n}",
"static u32 error_type;\nstatic u32 error_flags;\nstatic u64 error_param1;\nstatic u64 error_param2;\nstatic u64 error_param3;\nstatic u64 error_param4;\nstatic struct dentry *einj_debug_dir;",
"static int available_error_type_show(struct seq_file *m, void *v)\n{\n\tint rc;\n\tu32 available_error_type = 0;",
"\trc = einj_get_available_error_type(&available_error_type);\n\tif (rc)\n\t\treturn rc;\n\tif (available_error_type & 0x0001)\n\t\tseq_printf(m, \"0x00000001\\tProcessor Correctable\\n\");\n\tif (available_error_type & 0x0002)\n\t\tseq_printf(m, \"0x00000002\\tProcessor Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0004)\n\t\tseq_printf(m, \"0x00000004\\tProcessor Uncorrectable fatal\\n\");\n\tif (available_error_type & 0x0008)\n\t\tseq_printf(m, \"0x00000008\\tMemory Correctable\\n\");\n\tif (available_error_type & 0x0010)\n\t\tseq_printf(m, \"0x00000010\\tMemory Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0020)\n\t\tseq_printf(m, \"0x00000020\\tMemory Uncorrectable fatal\\n\");\n\tif (available_error_type & 0x0040)\n\t\tseq_printf(m, \"0x00000040\\tPCI Express Correctable\\n\");\n\tif (available_error_type & 0x0080)\n\t\tseq_printf(m, \"0x00000080\\tPCI Express Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0100)\n\t\tseq_printf(m, \"0x00000100\\tPCI Express Uncorrectable fatal\\n\");\n\tif (available_error_type & 0x0200)\n\t\tseq_printf(m, \"0x00000200\\tPlatform Correctable\\n\");\n\tif (available_error_type & 0x0400)\n\t\tseq_printf(m, \"0x00000400\\tPlatform Uncorrectable non-fatal\\n\");\n\tif (available_error_type & 0x0800)\n\t\tseq_printf(m, \"0x00000800\\tPlatform Uncorrectable fatal\\n\");",
"\treturn 0;\n}",
"static int available_error_type_open(struct inode *inode, struct file *file)\n{\n\treturn single_open(file, available_error_type_show, NULL);\n}",
"static const struct file_operations available_error_type_fops = {\n\t.open\t\t= available_error_type_open,\n\t.read\t\t= seq_read,\n\t.llseek\t\t= seq_lseek,\n\t.release\t= single_release,\n};",
"static int error_type_get(void *data, u64 *val)\n{\n\t*val = error_type;",
"\treturn 0;\n}",
"static int error_type_set(void *data, u64 val)\n{\n\tint rc;\n\tu32 available_error_type = 0;\n\tu32 tval, vendor;",
"\t/*\n\t * Vendor defined types have 0x80000000 bit set, and\n\t * are not enumerated by ACPI_EINJ_GET_ERROR_TYPE\n\t */\n\tvendor = val & ACPI5_VENDOR_BIT;\n\ttval = val & 0x7fffffff;",
"\t/* Only one error type can be specified */\n\tif (tval & (tval - 1))\n\t\treturn -EINVAL;\n\tif (!vendor) {\n\t\trc = einj_get_available_error_type(&available_error_type);\n\t\tif (rc)\n\t\t\treturn rc;\n\t\tif (!(val & available_error_type))\n\t\t\treturn -EINVAL;\n\t}\n\terror_type = val;",
"\treturn 0;\n}",
"DEFINE_SIMPLE_ATTRIBUTE(error_type_fops, error_type_get,\n\t\t\terror_type_set, \"0x%llx\\n\");",
"static int error_inject_set(void *data, u64 val)\n{\n\tif (!error_type)\n\t\treturn -EINVAL;",
"\treturn einj_error_inject(error_type, error_flags, error_param1, error_param2,\n\t\terror_param3, error_param4);\n}",
"DEFINE_SIMPLE_ATTRIBUTE(error_inject_fops, NULL,\n\t\t\terror_inject_set, \"%llu\\n\");",
"static int einj_check_table(struct acpi_table_einj *einj_tab)\n{\n\tif ((einj_tab->header_length !=\n\t (sizeof(struct acpi_table_einj) - sizeof(einj_tab->header)))\n\t && (einj_tab->header_length != sizeof(struct acpi_table_einj)))\n\t\treturn -EINVAL;\n\tif (einj_tab->header.length < sizeof(struct acpi_table_einj))\n\t\treturn -EINVAL;\n\tif (einj_tab->entries !=\n\t (einj_tab->header.length - sizeof(struct acpi_table_einj)) /\n\t sizeof(struct acpi_einj_entry))\n\t\treturn -EINVAL;",
"\treturn 0;\n}",
"static int __init einj_init(void)\n{\n\tint rc;\n\tacpi_status status;\n\tstruct dentry *fentry;\n\tstruct apei_exec_context ctx;",
"\tif (acpi_disabled)\n\t\treturn -ENODEV;",
"\tstatus = acpi_get_table(ACPI_SIG_EINJ, 0,\n\t\t\t\t(struct acpi_table_header **)&einj_tab);\n\tif (status == AE_NOT_FOUND)\n\t\treturn -ENODEV;\n\telse if (ACPI_FAILURE(status)) {\n\t\tconst char *msg = acpi_format_exception(status);\n\t\tpr_err(EINJ_PFX \"Failed to get table, %s\\n\", msg);\n\t\treturn -EINVAL;\n\t}",
"\trc = einj_check_table(einj_tab);\n\tif (rc) {\n\t\tpr_warning(FW_BUG EINJ_PFX \"EINJ table is invalid\\n\");\n\t\treturn -EINVAL;\n\t}",
"\trc = -ENOMEM;\n\teinj_debug_dir = debugfs_create_dir(\"einj\", apei_get_debugfs_dir());\n\tif (!einj_debug_dir)\n\t\tgoto err_cleanup;\n\tfentry = debugfs_create_file(\"available_error_type\", S_IRUSR,\n\t\t\t\t einj_debug_dir, NULL,\n\t\t\t\t &available_error_type_fops);\n\tif (!fentry)\n\t\tgoto err_cleanup;\n\tfentry = debugfs_create_file(\"error_type\", S_IRUSR | S_IWUSR,\n\t\t\t\t einj_debug_dir, NULL, &error_type_fops);\n\tif (!fentry)\n\t\tgoto err_cleanup;\n\tfentry = debugfs_create_file(\"error_inject\", S_IWUSR,\n\t\t\t\t einj_debug_dir, NULL, &error_inject_fops);\n\tif (!fentry)\n\t\tgoto err_cleanup;",
"\tapei_resources_init(&einj_resources);\n\teinj_exec_ctx_init(&ctx);\n\trc = apei_exec_collect_resources(&ctx, &einj_resources);\n\tif (rc)\n\t\tgoto err_fini;\n\trc = apei_resources_request(&einj_resources, \"APEI EINJ\");\n\tif (rc)\n\t\tgoto err_fini;\n\trc = apei_exec_pre_map_gars(&ctx);\n\tif (rc)\n\t\tgoto err_release;",
"\trc = -ENOMEM;\n\teinj_param = einj_get_parameter_address();\n\tif ((param_extension || acpi5) && einj_param) {\n\t\tfentry = debugfs_create_x32(\"flags\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_flags);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param1\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param1);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param2\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param2);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param3\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param3);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x64(\"param4\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &error_param4);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;",
"\t\tfentry = debugfs_create_x32(\"notrigger\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, ¬rigger);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t}",
"\tif (vendor_dev[0]) {\n\t\tvendor_blob.data = vendor_dev;\n\t\tvendor_blob.size = strlen(vendor_dev);\n\t\tfentry = debugfs_create_blob(\"vendor\", S_IRUSR,\n\t\t\t\t\t einj_debug_dir, &vendor_blob);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t\tfentry = debugfs_create_x32(\"vendor_flags\", S_IRUSR | S_IWUSR,\n\t\t\t\t\t einj_debug_dir, &vendor_flags);\n\t\tif (!fentry)\n\t\t\tgoto err_unmap;\n\t}",
"\tpr_info(EINJ_PFX \"Error INJection is initialized.\\n\");",
"\treturn 0;",
"err_unmap:\n\tif (einj_param) {\n\t\tacpi_size size = (acpi5) ?\n\t\t\tsizeof(struct set_error_type_with_address) :\n\t\t\tsizeof(struct einj_parameter);",
"\t\tacpi_os_unmap_iomem(einj_param, size);\n\t}\n\tapei_exec_post_unmap_gars(&ctx);\nerr_release:\n\tapei_resources_release(&einj_resources);\nerr_fini:\n\tapei_resources_fini(&einj_resources);\nerr_cleanup:\n\tdebugfs_remove_recursive(einj_debug_dir);",
"\treturn rc;\n}",
"static void __exit einj_exit(void)\n{\n\tstruct apei_exec_context ctx;",
"\tif (einj_param) {\n\t\tacpi_size size = (acpi5) ?\n\t\t\tsizeof(struct set_error_type_with_address) :\n\t\t\tsizeof(struct einj_parameter);",
"\t\tacpi_os_unmap_iomem(einj_param, size);\n\t}\n\teinj_exec_ctx_init(&ctx);\n\tapei_exec_post_unmap_gars(&ctx);\n\tapei_resources_release(&einj_resources);\n\tapei_resources_fini(&einj_resources);\n\tdebugfs_remove_recursive(einj_debug_dir);\n}",
"module_init(einj_init);\nmodule_exit(einj_exit);",
"MODULE_AUTHOR(\"Huang Ying\");\nMODULE_DESCRIPTION(\"APEI Error INJection support\");\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [523], "buggy_code_start_loc": [31], "filenames": ["drivers/acpi/apei/einj.c"], "fixing_code_end_loc": [528], "fixing_code_start_loc": [32], "message": "The einj_error_inject function in drivers/acpi/apei/einj.c in the Linux kernel allows local users to simulate hardware errors and consequently cause a denial of service by leveraging failure to disable APEI error injection through EINJ when securelevel is set.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:-:*:*:*:*:*:*:*", "matchCriteriaId": "703AF700-7A70-47E2-BC3A-7FD03B3CA9C1", "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:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "142AD0DD-4CF3-4D74-9442-459CE3347E3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The einj_error_inject function in drivers/acpi/apei/einj.c in the Linux kernel allows local users to simulate hardware errors and consequently cause a denial of service by leveraging failure to disable APEI error injection through EINJ when securelevel is set."}, {"lang": "es", "value": "La funci\u00f3n einj_error_inject en drivers/acpi/apei/einj.c en el kernel de Linux permite que usuarios locales simulen errores de hardware y, consecuentemente, provoquen una denegaci\u00f3n de servicio (DoS) aprovechando el error a la hora de deshabilitar la inyecci\u00f3n de errores APEI mediante EINJ cuando est\u00e1 establecido securelevel."}], "evaluatorComment": null, "id": "CVE-2016-3695", "lastModified": "2018-01-10T16:44:01.997", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/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-12-29T15:29:00.580", "references": [{"source": "secalert@redhat.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/102327"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1322755"}, {"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/mjg59/linux/commit/d7a6be58edc01b1c66ecd8fcc91236bfbce0a420"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/mjg59/linux/commit/d7a6be58edc01b1c66ecd8fcc91236bfbce0a420"}, "type": "CWE-74"}
| 314
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/**\n ** BigBlueButton open source conferencing system - http://www.bigbluebutton.org/\n *\n * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below).\n *\n * This program is free software; you can redistribute it and/or modify it under the\n * terms of the GNU Lesser General Public License as published by the Free Software\n * Foundation; either version 3.0 of the License, or (at your option) any later\n * version.\n *\n * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along\n * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>.\n *\n */\npackage org.bigbluebutton.web.controllers",
"import com.google.gson.Gson\nimport grails.web.context.ServletContextHolder\nimport groovy.json.JsonBuilder\nimport org.apache.commons.codec.binary.Base64\nimport org.apache.commons.io.FilenameUtils\nimport org.apache.commons.lang.RandomStringUtils\nimport org.apache.commons.lang.StringUtils\nimport org.bigbluebutton.api.*\nimport org.bigbluebutton.api.domain.Config\nimport org.bigbluebutton.api.domain.GuestPolicy\nimport org.bigbluebutton.api.domain.Meeting\nimport org.bigbluebutton.api.domain.UserSession\nimport org.bigbluebutton.api.util.ParamsUtil\nimport org.bigbluebutton.api.util.ResponseBuilder\nimport org.bigbluebutton.presentation.PresentationUrlDownloadService\nimport org.bigbluebutton.presentation.UploadedPresentation\nimport org.bigbluebutton.web.services.PresentationService\nimport org.bigbluebutton.web.services.turn.StunTurnService\nimport org.bigbluebutton.web.services.turn.TurnEntry\nimport org.bigbluebutton.web.services.turn.StunServer\nimport org.bigbluebutton.web.services.turn.RemoteIceCandidate\nimport org.json.JSONArray",
"import javax.servlet.ServletRequest",
"class ApiController {\n private static final Integer SESSION_TIMEOUT = 14400 // 4 hours\n private static final String CONTROLLER_NAME = 'ApiController'\n protected static final String RESP_CODE_SUCCESS = 'SUCCESS'\n protected static final String RESP_CODE_FAILED = 'FAILED'\n private static final String ROLE_MODERATOR = \"MODERATOR\"\n private static final String ROLE_ATTENDEE = \"VIEWER\"\n protected static Boolean REDIRECT_RESPONSE = true",
" MeetingService meetingService;\n PresentationService presentationService\n ParamsProcessorUtil paramsProcessorUtil\n ClientConfigService configService\n PresentationUrlDownloadService presDownloadService\n StunTurnService stunTurnService\n ResponseBuilder responseBuilder = initResponseBuilder()",
" def initResponseBuilder = {\n String protocol = this.getClass().getResource(\"\").getProtocol();\n if (Objects.equals(protocol, \"jar\")) {\n // Application running inside a JAR file\n responseBuilder = new ResponseBuilder(getClass().getClassLoader(), \"/WEB-INF/freemarker\")\n } else if (Objects.equals(protocol, \"file\")) {\n // Application unzipped and running outside a JAR file\n String templateLoc = ServletContextHolder.servletContext.getRealPath(\"/WEB-INF/freemarker\")\n // We should never have a null `templateLoc`\n responseBuilder = new ResponseBuilder(new File(templateLoc))\n }\n }",
" /* general methods */\n def index = {\n log.debug CONTROLLER_NAME + \"#index\"\n response.addHeader(\"Cache-Control\", \"no-cache\")",
" withFormat {\n xml {\n render(text: responseBuilder.buildMeetingVersion(paramsProcessorUtil.getApiVersion(), RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }",
" /***********************************\n * CREATE (API)\n ***********************************/\n def create = {\n String API_CALL = 'create'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"\n log.debug request.getParameterMap().toMapString()",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors();\n paramsProcessorUtil.processRequiredCreateParams(params, errors);",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree with the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" Meeting newMeeting = paramsProcessorUtil.processCreateParams(params)",
" if (meetingService.createMeeting(newMeeting)) {\n // See if the request came with pre-uploading of presentation.\n uploadDocuments(newMeeting); //\n respondWithConference(newMeeting, null, null)\n } else {\n // Translate the external meeting id into an internal meeting id.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID);\n Meeting existing = meetingService.getNotEndedMeetingWithId(internalMeetingId);\n if (existing != null) {\n log.debug \"Existing conference found\"\n Map<String, Object> updateParams = paramsProcessorUtil.processUpdateCreateParams(params);\n if (existing.getViewerPassword().equals(params.get(\"attendeePW\")) && existing.getModeratorPassword().equals(params.get(\"moderatorPW\"))) {\n //paramsProcessorUtil.updateMeeting(updateParams, existing);\n // trying to create a conference a second time, return success, but give extra info\n // Ignore pre-uploaded presentations. We only allow uploading of presentation once.\n //uploadDocuments(existing);\n respondWithConference(existing, \"duplicateWarning\", \"This conference was already in existence and may currently be in progress.\");\n } else {\n // BEGIN - backward compatibility\n invalid(\"idNotUnique\", \"A meeting already exists with that meeting ID. Please use a different meeting ID.\");\n return\n // END - backward compatibility",
" // enforce meetingID unique-ness\n errors.nonUniqueMeetingIdError()\n respondWithErrors(errors)\n }",
" return\n }\n }\n }",
"\n /**********************************************\n * JOIN API\n *********************************************/\n def join = {\n String API_CALL = 'join'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"\n ApiErrors errors = new ApiErrors()",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\", REDIRECT_RESPONSE)\n return\n }",
" //checking for an empty username or for a username containing whitespaces only\n if (!StringUtils.isEmpty(params.fullName)) {\n params.fullName = StringUtils.strip(params.fullName);\n if (StringUtils.isEmpty(params.fullName)) {\n invalid(\"missingParamFullName\", \"You must specify a name for the attendee who will be joining the meeting.\", REDIRECT_RESPONSE);\n return\n }\n } else {\n invalid(\"missingParamFullName\", \"You must specify a name for the attendee who will be joining the meeting.\", REDIRECT_RESPONSE);\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\", REDIRECT_RESPONSE)\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\", REDIRECT_RESPONSE)\n return\n }",
" if (StringUtils.isEmpty(params.password)) {\n invalid(\"invalidPassword\", \"You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference.\", REDIRECT_RESPONSE);\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\", REDIRECT_RESPONSE)\n return\n }",
" // END - backward compatibility",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" Boolean authenticated = false;",
" Boolean guest = false;\n if (!StringUtils.isEmpty(params.guest)) {\n guest = Boolean.parseBoolean(params.guest)\n } else {\n // guest param has not been passed. Make user as\n // authenticated by default. (ralam july 3, 2018)\n authenticated = true\n }",
"\n if (!StringUtils.isEmpty(params.auth)) {\n authenticated = Boolean.parseBoolean(params.auth)\n }",
" Boolean joinViaHtml5 = false;\n if (!StringUtils.isEmpty(params.joinViaHtml5)) {\n joinViaHtml5 = Boolean.parseBoolean(params.joinViaHtml5)\n }",
" // Do we have a name for the user joining? If none, complain.\n if (!StringUtils.isEmpty(params.fullName)) {\n params.fullName = StringUtils.strip(params.fullName);",
"",
" if (StringUtils.isEmpty(params.fullName)) {\n errors.missingParamError(\"fullName\");\n }\n } else {\n errors.missingParamError(\"fullName\");\n }\n String fullName = ParamsUtil.stripHTMLTags(params.fullName)",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
" // Do we have a password? If not, complain.\n String attPW = params.password\n if (StringUtils.isEmpty(attPW)) {\n errors.missingParamError(\"password\");\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);",
" log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidMeetingIdentifier\", \"The meeting ID that you supplied did not match any existing meetings\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.invalidMeetingIdError();\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // the createTime mismatch with meeting's createTime, complain\n // In the future, the createTime param will be required\n if (params.createTime != null) {\n long createTime = 0;\n try {\n createTime = Long.parseLong(params.createTime);\n } catch (Exception e) {\n log.warn(\"could not parse createTime param\");\n createTime = -1;\n }\n if (createTime != meeting.getCreateTime()) {\n // BEGIN - backward compatibility\n invalid(\"mismatchCreateTimeParam\", \"The createTime parameter submitted mismatches with the current meeting.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.mismatchCreateTimeParam();\n respondWithErrors(errors, REDIRECT_RESPONSE);\n return\n }\n }",
" // Is this user joining a meeting that has been ended. If so, complain.\n if (meeting.isForciblyEnded()) {\n // BEGIN - backward compatibility\n invalid(\"meetingForciblyEnded\", \"You can not re-join a meeting that has already been forcibly ended. However, once the meeting is removed from memory (according to the timeout configured on this server, you will be able to once again create a meeting with the same meeting ID\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.meetingForciblyEndedError();\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // Now determine if this user is a moderator or a viewer.\n String role = null;\n if (meeting.getModeratorPassword().equals(attPW)) {\n role = Meeting.ROLE_MODERATOR\n } else if (meeting.getViewerPassword().equals(attPW)) {\n role = Meeting.ROLE_ATTENDEE\n }",
" if (role == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidPassword\", \"You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.invalidPasswordError()\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // We preprend \"w_\" to our internal meeting Id to indicate that this is a web user.\n // For users joining using the phone, we will prepend \"v_\" so it will be easier\n // to distinguish users who doesn't have a web client. (ralam june 12, 2017)\n String internalUserID = \"w_\" + RandomStringUtils.randomAlphanumeric(12).toLowerCase()",
" String authToken = RandomStringUtils.randomAlphanumeric(12).toLowerCase()",
" String sessionToken = RandomStringUtils.randomAlphanumeric(16).toLowerCase()",
" String externUserID = params.userID\n if (StringUtils.isEmpty(externUserID)) {\n externUserID = internalUserID\n }",
" //Return a Map with the user custom data\n Map<String, String> userCustomData = paramsProcessorUtil.getUserCustomData(params);",
" //Currently, it's associated with the externalUserID\n if (userCustomData.size() > 0)\n meetingService.addUserCustomData(meeting.getInternalId(), externUserID, userCustomData);",
" String configxml = null;",
" if (!StringUtils.isEmpty(params.configToken)) {\n Config conf = meeting.getConfig(params.configToken);\n if (conf == null) {\n // Check if this config is one of our pre-built config\n configxml = configService.getConfig(params.configToken)\n if (configxml == null) {\n // BEGIN - backward compatibility\n invalid(\"noConfigFound\", \"We could not find a config for this request.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.noConfigFound();\n respondWithErrors(errors);\n }\n } else {\n configxml = conf.config;\n }\n } else {\n Config conf = meeting.getDefaultConfig();\n configxml = conf.config;\n }",
" // Do not fail if there's no default config.xml, needed for an HTML5 client only scenario",
" String guestStatusVal = meeting.calcGuestStatus(role, guest, authenticated)",
" UserSession us = new UserSession();\n us.authToken = authToken;\n us.internalUserId = internalUserID\n us.conferencename = meeting.getName()\n us.meetingID = meeting.getInternalId()\n us.externMeetingID = meeting.getExternalId()\n us.externUserID = externUserID\n us.fullname = fullName\n us.role = role\n us.conference = meeting.getInternalId()\n us.room = meeting.getInternalId()\n us.voicebridge = meeting.getTelVoice()\n us.webvoiceconf = meeting.getWebVoice()\n us.mode = \"LIVE\"\n us.record = meeting.isRecord()\n us.welcome = meeting.getWelcomeMessage()\n us.guest = guest\n us.authed = authenticated\n us.guestStatus = guestStatusVal\n us.logoutUrl = meeting.getLogoutUrl()\n us.configXML = configxml;",
" if (!StringUtils.isEmpty(params.defaultLayout)) {\n us.defaultLayout = params.defaultLayout;\n }",
" if (!StringUtils.isEmpty(params.avatarURL)) {\n us.avatarURL = params.avatarURL;\n } else {\n us.avatarURL = meeting.defaultAvatarURL\n }",
" String meetingId = meeting.getInternalId()",
" if (hasReachedMaxParticipants(meeting, us)) {\n // BEGIN - backward compatibility\n invalid(\"maxParticipantsReached\", \"The number of participants allowed for this meeting has been reached.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.maxParticipantsReached();\n respondWithErrors(errors, REDIRECT_RESPONSE);\n return;\n }",
" // Register user into the meeting.\n meetingService.registerUser(\n us.meetingID,\n us.internalUserId,\n us.fullname,\n us.role,\n us.externUserID,\n us.authToken,\n us.avatarURL,\n us.guest,\n us.authed,\n guestStatusVal\n )",
" //Identify which of these to logs should be used. sessionToken or user-token\n log.info(\"Session sessionToken for \" + us.fullname + \" [\" + session[sessionToken] + \"]\")\n log.info(\"Session user-token for \" + us.fullname + \" [\" + session['user-token'] + \"]\")\n session.setMaxInactiveInterval(SESSION_TIMEOUT);",
" //check if exists the param redirect\n boolean redirectClient = true;\n String clientURL = paramsProcessorUtil.getDefaultClientUrl();",
" // server-wide configuration:\n // Depending on configuration, prefer the HTML5 client over Flash for moderators\n if (paramsProcessorUtil.getModeratorsJoinViaHTML5Client() && role == ROLE_MODERATOR) {\n joinViaHtml5 = true\n }",
" // Depending on configuration, prefer the HTML5 client over Flash for attendees\n if (paramsProcessorUtil.getAttendeesJoinViaHTML5Client() && role == ROLE_ATTENDEE) {\n joinViaHtml5 = true\n }",
" // single client join configuration:\n // Depending on configuration, prefer the HTML5 client over Flash client\n if (joinViaHtml5) {\n clientURL = paramsProcessorUtil.getHTML5ClientUrl();\n } else {\n if (!StringUtils.isEmpty(params.clientURL)) {\n clientURL = params.clientURL;\n }\n }",
" if (!StringUtils.isEmpty(params.redirect)) {\n try {\n redirectClient = Boolean.parseBoolean(params.redirect);\n } catch (Exception e) {\n redirectClient = true;\n }\n }",
" String msgKey = \"successfullyJoined\"\n String msgValue = \"You have joined successfully.\"",
" // Keep track of the client url in case this needs to wait for\n // approval as guest. We need to be able to send the user to the\n // client after being approved by moderator.\n us.clientUrl = clientURL + \"?sessionToken=\" + sessionToken",
" session[sessionToken] = sessionToken\n meetingService.addUserSession(sessionToken, us);",
" // Process if we send the user directly to the client or\n // have it wait for approval.\n String destUrl = clientURL + \"?sessionToken=\" + sessionToken\n if (guestStatusVal.equals(GuestPolicy.WAIT)) {\n String guestWaitUrl = paramsProcessorUtil.getDefaultGuestWaitURL();\n destUrl = guestWaitUrl + \"?sessionToken=\" + sessionToken\n msgKey = \"guestWait\"\n msgValue = \"Guest waiting for approval to join meeting.\"\n } else if (guestStatusVal.equals(GuestPolicy.DENY)) {\n destUrl = meeting.getLogoutUrl()\n msgKey = \"guestDeny\"\n msgValue = \"Guest denied to join meeting.\"\n }",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"join_api\");\n logData.put(\"description\", \"Handle JOIN API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" if (redirectClient) {\n log.info(\"Redirecting to ${destUrl}\");\n redirect(url: destUrl);\n } else {\n log.info(\"Successfully joined. Sending XML response.\");\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildJoinMeeting(us, session[sessionToken], guestStatusVal, destUrl, msgKey, msgValue, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /*******************************************\n * IS_MEETING_RUNNING API\n *******************************************/\n def isMeetingRunning = {\n String API_CALL = 'isMeetingRunning'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
"\n if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);\n log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n boolean isRunning = meeting != null && meeting.isRunning();",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(contentType: \"text/xml\") {\n render(text: responseBuilder.buildIsMeetingRunning(isRunning, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /************************************\n * END API\n ************************************/\n def end = {\n String API_CALL = \"end\"",
" log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (StringUtils.isEmpty(params.password)) {\n invalid(\"invalidPassword\", \"You must supply the moderator password for this call.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
" // Do we have a password? If not, complain.\n String modPW = params.password\n if (StringUtils.isEmpty(modPW)) {\n errors.missingParamError(\"password\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);\n log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find a meeting with that meeting ID - perhaps the meeting is not yet running?\");\n return;\n // END - backward compatibility",
" errors.invalidMeetingIdError();\n respondWithErrors(errors)\n return;\n }",
" if (meeting.getModeratorPassword().equals(modPW) == false) {\n // BEGIN - backward compatibility\n invalid(\"invalidPassword\", \"You must supply the moderator password for this call.\");\n return;\n // END - backward compatibility",
" errors.invalidPasswordError();\n respondWithErrors(errors)\n return;\n }",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", meeting.getInternalId());\n logData.put(\"extMeetingid\", meeting.getExternalId());\n logData.put(\"name\", meeting.getName());\n logData.put(\"logCode\", \"end_api\");\n logData.put(\"description\", \"Handle END API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" meetingService.endMeeting(meeting.getInternalId());",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(contentType: \"text/xml\") {\n render(text: responseBuilder.buildEndRunning(\"sentEndMeetingRequest\", \"A request to end the meeting was sent. Please wait a few seconds, and then use the getMeetingInfo or isMeetingRunning API calls to verify that it was ended.\", RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /*****************************************\n * GETMEETINGINFO API\n *****************************************/\n def getMeetingInfo = {\n String API_CALL = \"getMeetingInfo\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);\n log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find a meeting with that meeting ID\");\n return;\n // END - backward compatibility",
" errors.invalidMeetingIdError();\n respondWithErrors(errors)\n return;\n }",
" withFormat {\n xml {\n render(text: responseBuilder.buildGetMeetingInfoResponse(meeting, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }",
" /************************************\n * GETMEETINGS API\n ************************************/\n def getMeetingsHandler = {\n String API_CALL = \"getMeetings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" Collection<Meeting> mtgs = meetingService.getMeetings();",
" if (mtgs == null || mtgs.isEmpty()) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildGetMeetingsResponse(mtgs, \"noMeetings\", \"no meetings were found on this server\", RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")",
" withFormat {\n xml {\n render(text: responseBuilder.buildGetMeetingsResponse(mtgs, null, null, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /************************************\n * GETSESSIONS API\n ************************************/\n def getSessionsHandler = {\n String API_CALL = \"getSessions\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" Collection<UserSession> sssns = meetingService.getSessions();",
" if (sssns == null || sssns.isEmpty()) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildGetSessionsResponse(sssns, \"noSessions\", \"no sessions were found on this serverr\", RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(contentType: \"text/xml\") {\n render(text: responseBuilder.buildGetSessionsResponse(sssns, null, null, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }\n }",
"\n private static Map<String, String[]> getParameters(ServletRequest request) {\n // Copy the parameters into our own Map as we can't pass the paramMap\n // from the request as it's an unmodifiable map.\n Map<String, String[]> reqParams = new HashMap<String, String[]>();\n Map<String, String[]> unModReqParams = request.getParameterMap();",
" SortedSet<String> keys = new TreeSet<String>(unModReqParams.keySet());",
" for(String key : keys) {\n reqParams.put(key, unModReqParams.get(key));\n }",
" return reqParams;\n }",
" /***********************************************\n * POLL API\n ***********************************************/\n def setPollXML = {\n String API_CALL = \"setPollXML\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.pollXML)) {\n invalid(\"configXMLError\", \"You did not pass a poll XML\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" // Translate the external meeting id into an internal meeting id.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID);\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidMeetingIdentifier\", \"The meeting ID that you supplied did not match any existing meetings\");\n return;\n // END - backward compatibility\n }",
" Map<String, String[]> reqParams = getParameters(request)",
" String pollXML = params.pollXML",
" String decodedPollXML;",
" try {\n decodedPollXML = URLDecoder.decode(pollXML, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n log.error \"Couldn't decode poll XML.\", e\n invalid(\"pollXMLError\", \"Cannot decode poll XML\")\n return;\n }",
" if (!paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n invalid(\"pollXMLChecksumError\", \"pollXMLChecksumError: request did not pass the checksum security check.\")\n }\n }\n } else {\n def pollxml = new XmlSlurper().parseText(decodedPollXML);",
" pollxml.children().each { poll ->\n String title = poll.title.text();\n String question = poll.question.text();\n String questionType = poll.questionType.text();",
" ArrayList<String> answers = new ArrayList<String>();\n poll.answers.children().each { answer ->\n answers.add(answer.text());\n }",
" //send poll to BigBlueButton Apps\n meetingService.createdPolls(meeting.getInternalId(), title, question, questionType, answers);\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode></response>\", contentType: \"text/xml\")\n }\n }\n }\n }",
" /***********************************************\n * CONFIG API\n ***********************************************/\n def setConfigXML = {\n String API_CALL = \"setConfigXML\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.configXML)) {\n invalid(\"configXMLError\", \"You did not pass a config XML\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" // Translate the external meeting id into an internal meeting id.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID);\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidMeetingIdentifier\", \"The meeting ID that you supplied did not match any existing meetings\");\n return;\n // END - backward compatibility\n }",
" Map<String, String[]> reqParams = getParameters(request)",
" String configXML = params.configXML",
" String decodedConfigXML;",
" try {\n decodedConfigXML = URLDecoder.decode(configXML, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n log.error(\"Couldn't decode config XML.\");\n invalid(\"configXMLError\", \"Cannot decode config XML\")\n return;\n }",
" if (!paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n invalid(\"configXMLChecksumError\", \"configXMLChecksumError: request did not pass the checksum security check.\")\n }\n }\n } else {\n boolean defaultConfig = false;",
" if (!StringUtils.isEmpty(params.defaultConfig)) {\n try {\n defaultConfig = Boolean.parseBoolean(params.defaultConfig);\n } catch (Exception e) {\n defaultConfig = false;\n }\n }",
" String token = meeting.storeConfig(defaultConfig, decodedConfigXML);\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><configToken>$token</configToken></response>\", contentType: \"text/xml\")\n }\n }\n }\n }",
" def getDefaultConfigXML = {",
" String API_CALL = \"getDefaultConfigXML\"\n ApiErrors errors = new ApiErrors();",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
"\n // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" String defConfigXML = paramsProcessorUtil.getDefaultConfigXML();\n if (StringUtils.isEmpty(defConfigXML)) {\n // BEGIN - backward compatibility\n invalid(\"noConfigFound\", \"We could not find a config for this request.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.noConfigFound();\n respondWithErrors(errors);\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n render text: defConfigXML, contentType: 'text/xml'\n }",
" def configXML = {\n String API_CALL = 'configXML'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()\n boolean reject = false\n String sessionToken = sanitizeSessionToken(params.sessionToken)\n if (!hasValidSession(sessionToken)) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildConfgXmlReject(\"Could not find conference.\", logoutUrl, RESP_CODE_FAILED), contentType: \"text/xml\")\n }\n }\n } else {\n UserSession us = getUserSession(sessionToken)\n if (StringUtils.isEmpty(us.configXML)) {\n // BEGIN - backward compatibility\n invalid(\"noConfigFound\", \"We could not find a config for this request.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.noConfigFound();\n respondWithErrors(errors);\n }",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingId\", us.meetingID);\n logData.put(\"externalMeetingId\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userId\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"handle_configxml_api\");\n logData.put(\"description\", \"Handling ConfigXml API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n render text: us.configXML, contentType: 'text/xml'\n }\n }",
" /**********************************************\n * GUEST WAIT API\n *********************************************/\n def guestWaitHandler = {\n String API_CALL = 'guestWait'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"\n ApiErrors errors = new ApiErrors()\n boolean reject = false;\n String sessionToken = sanitizeSessionToken(params.sessionToken)",
" UserSession us = getUserSession(sessionToken);\n Meeting meeting = null;",
" if (us == null) {\n log.debug(\"No user with session token.\")\n reject = true;\n } else {\n meeting = meetingService.getMeeting(us.meetingID);\n if (meeting == null || meeting.isForciblyEnded()) {\n log.debug(\"Meeting not found.\")\n reject = true\n }\n }",
" // Determine the logout url so we can send the user there.\n String logoutUrl = us != null ? us.logoutUrl : paramsProcessorUtil.getDefaultLogoutUrl()",
" if (reject) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n message \"Could not process waiting guest.\"\n logoutURL logoutUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n } else {\n //check if exists the param redirect\n boolean redirectClient = true;",
" // Get the client url we stored in the join api call before\n // being told to wait.\n String clientURL = us.clientUrl;\n log.info(\"clientURL = \" + clientURL)\n log.info(\"redirect = .\" + redirectClient)\n if (!StringUtils.isEmpty(params.redirect)) {\n try {\n redirectClient = Boolean.parseBoolean(params.redirect);\n log.info(\"redirect 2 = .\" + redirectClient)\n } catch (Exception e) {\n redirectClient = true;\n }\n }",
" // The client url is ovewriten. Let's allow it.\n if (!StringUtils.isEmpty(params.clientURL)) {\n clientURL = params.clientURL;\n }",
" String guestWaitStatus = us.guestStatus",
" log.debug(\"GuestWaitStatus = \" + guestWaitStatus)",
" String msgKey = \"guestAllowed\"\n String msgValue = \"Guest allowed to join meeting.\"",
" String destUrl = clientURL\n log.debug(\"destUrl = \" + destUrl)",
"\n if (guestWaitStatus.equals(GuestPolicy.WAIT)) {\n clientURL = paramsProcessorUtil.getDefaultGuestWaitURL();\n destUrl = clientURL + \"?sessionToken=\" + sessionToken\n log.debug(\"GuestPolicy.WAIT - destUrl = \" + destUrl)\n msgKey = \"guestWait\"\n msgValue = \"Guest waiting for approval to join meeting.\"\n // We force the response to not do a redirect. Otherwise,\n // the client would just be redirecting into this endpoint.\n redirectClient = false",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"guest_wait\");\n logData.put(\"description\", \"Guest waiting for approval.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" } else if (guestWaitStatus.equals(GuestPolicy.DENY)) {\n destUrl = meeting.getLogoutUrl()\n msgKey = \"guestDenied\"\n msgValue = \"Guest denied to join meeting.\"",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"guest_denied\");\n logData.put(\"description\", \"Guest denied.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);\n }",
" if (redirectClient) {\n log.info(\"Redirecting to ${destUrl}\");\n redirect(url: destUrl);\n } else {\n log.info(\"Successfully joined. Sending XML response.\");\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_SUCCESS\n messageKey msgKey\n message msgValue\n meeting_id us.meetingID\n user_id us.internalUserId\n auth_token us.authToken\n session_token session[sessionToken]\n guestStatus guestWaitStatus\n url destUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }\n }",
" /***********************************************\n * ENTER API\n ***********************************************/\n def enter = {\n boolean reject = false;",
" String sessionToken = sanitizeSessionToken(params.sessionToken)\n UserSession us = getUserSession(sessionToken);\n Meeting meeting = null;",
" String respMessage = \"Session \" + sessionToken + \" not found.\"",
" if (!hasValidSession(sessionToken)) {\n reject = true;\n } else {\n meeting = meetingService.getMeeting(us.meetingID);\n if (meeting == null || meeting.isForciblyEnded()) {\n reject = true\n respMessage = \"Meeting not found or ended for session \" + sessionToken + \".\"\n } else {\n if (hasReachedMaxParticipants(meeting, us)) {\n reject = true;\n respMessage = \"The number of participants allowed for this meeting has been reached.\";\n } else {\n meeting.userEntered(us.internalUserId);\n }\n }\n if (us.guestStatus.equals(GuestPolicy.DENY)) {\n respMessage = \"User denied for user with session \" + sessionToken + \".\"\n reject = true\n }\n }",
" if (reject) {\n // Determine the logout url so we can send the user there.\n String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()",
" if (us != null) {\n logoutUrl = us.logoutUrl\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n message respMessage\n logoutURL logoutUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n } else {",
" Map<String, String> userCustomData = paramsProcessorUtil.getUserCustomData(params);",
" // Generate a new userId for this user. This prevents old connections from\n // removing the user when the user reconnects after being disconnected. (ralam jan 22, 2015)\n // We use underscore (_) to associate userid with the user. We are also able to track\n // how many times a user reconnects or refresh the browser.\n String newInternalUserID = us.internalUserId //+ \"_\" + us.incrementConnectionNum()",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", newInternalUserID);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"handle_enter_api\");\n logData.put(\"description\", \"Handling ENTER API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_SUCCESS\n fullname us.fullname\n confname us.conferencename\n meetingID us.meetingID\n externMeetingID us.externMeetingID\n externUserID us.externUserID\n internalUserID newInternalUserID\n authToken us.authToken\n role us.role\n guest us.guest\n guestStatus us.guestStatus\n conference us.conference\n room us.room\n voicebridge us.voicebridge\n dialnumber meeting.getDialNumber()\n webvoiceconf us.webvoiceconf\n mode us.mode\n record us.record\n isBreakout meeting.isBreakout()\n logoutTimer meeting.getLogoutTimer()\n allowStartStopRecording meeting.getAllowStartStopRecording()\n welcome us.welcome\n if (!StringUtils.isEmpty(meeting.moderatorOnlyMessage) && us.role.equals(ROLE_MODERATOR)) {\n modOnlyMessage meeting.moderatorOnlyMessage\n }\n if (!StringUtils.isEmpty(meeting.bannerText)) {\n bannerText meeting.getBannerText()\n bannerColor meeting.getBannerColor()\n }\n customLogoURL meeting.getCustomLogoURL()\n customCopyright meeting.getCustomCopyright()\n muteOnStart meeting.getMuteOnStart()\n allowModsToUnmuteUsers meeting.getAllowModsToUnmuteUsers()\n logoutUrl us.logoutUrl\n defaultLayout us.defaultLayout\n avatarURL us.avatarURL\n if (meeting.breakoutRoomsParams != null) {\n breakoutRooms {\n enabled meeting.breakoutRoomsParams.enabled\n record meeting.breakoutRoomsParams.record\n privateChatEnabled meeting.breakoutRoomsParams.privateChatEnabled\n }\n }\n customdata (\n meeting.getUserCustomData(us.externUserID).collect { k, v ->\n [\"$k\": v]\n }\n )\n metadata (\n meeting.getMetadata().collect { k, v ->\n [\"$k\": v]\n }\n )\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" /***********************************************\n * STUN/TURN API\n ***********************************************/\n def stuns = {\n boolean reject = false;",
" String sessionToken = sanitizeSessionToken(params.sessionToken)\n UserSession us = getUserSession(sessionToken);\n Meeting meeting = null;",
" if (!hasValidSession(sessionToken)) {\n reject = true;\n } else {\n meeting = meetingService.getMeeting(us.meetingID);\n if (meeting == null || meeting.isForciblyEnded()) {\n reject = true\n }\n }",
" if (reject) {\n String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder {\n returncode RESP_CODE_FAILED\n message \"Could not find conference.\"\n logoutURL logoutUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n } else {\n Set<StunServer> stuns = stunTurnService.getStunServers()\n Set<TurnEntry> turns = stunTurnService.getStunAndTurnServersFor(us.internalUserId)\n Set<RemoteIceCandidate> candidates = stunTurnService.getRemoteIceCandidates()",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder {\n stunServers (\n stuns.collect { stun ->\n [url: stun.url]\n }\n )\n turnServers (\n turns.collect { turn ->\n [\n username: turn.username,\n password: turn.password,\n url: turn.url,\n ttl: turn.ttl\n ]\n }\n )\n remoteIceCandidates (\n candidates.collect { candidate ->\n [ip: candidate.ip ]\n }\n )\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" /*************************************************\n * SIGNOUT API\n *************************************************/\n def signOut = {",
" String sessionToken = sanitizeSessionToken(params.sessionToken)",
" Meeting meeting = null;",
" if (sessionToken != null) {",
" UserSession us = meetingService.removeUserSessionWithAuthToken(sessionToken);\n if (us != null) {\n Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"message\", \"handle_signout_api\");\n logData.put(\"logCode\", \"signout_api\");\n logData.put(\"description\", \"Handling SIGNOUT API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);\n log.info(\" --analytics-- data=\" + logStr);\n } else {\n log.info(\"Could not find user session for session token {}\", sessionToken)\n }",
"\n session.removeAttribute(sessionToken)\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode></response>\", contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * GET_RECORDINGS API\n ******************************************************/\n def getRecordingsHandler = {\n String API_CALL = \"getRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n respondWithErrors(errors)\n return\n }",
" log.debug request.getQueryString()",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" List<String> externalMeetingIds = new ArrayList<String>();\n if (!StringUtils.isEmpty(params.meetingID)) {\n externalMeetingIds = paramsProcessorUtil.decodeIds(params.meetingID);\n }",
" ArrayList<String> internalRecordIds = new ArrayList<String>()\n if (!StringUtils.isEmpty(params.recordID)) {\n internalRecordIds = paramsProcessorUtil.decodeIds(params.recordID)\n }",
" ArrayList<String> states = new ArrayList<String>()\n if (!StringUtils.isEmpty(params.state)) {\n states = paramsProcessorUtil.decodeIds(params.state)\n }",
" // Everything is good so far.\n if (internalRecordIds.size() == 0 && externalMeetingIds.size() > 0) {\n // No recordIDs, process the request based on meetingID(s)\n // Translate the external meeting ids to internal meeting ids (which is the seed for the recordIDs).\n internalRecordIds = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingIds);\n }",
" for(String intRecId : internalRecordIds) {\n log.debug intRecId\n }",
" Map<String, String> metadataFilters = ParamsProcessorUtil.processMetaParam(params);",
" def getRecordingsResult = meetingService.getRecordings2x(internalRecordIds, states, metadataFilters)",
" withFormat {\n xml {\n render(text: getRecordingsResult, contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * PUBLISH_RECORDINGS API\n ******************************************************/\n def publishRecordings = {\n String API_CALL = \"publishRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.recordID)) {\n invalid(\"missingParamRecordID\", \"You must specify a recordID.\");\n return\n }",
" if (StringUtils.isEmpty(params.publish)) {\n invalid(\"missingParamPublish\", \"You must specify a publish value true or false.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a recording id? If none, complain.\n String recordId = params.recordID\n if (StringUtils.isEmpty(recordId)) {\n errors.missingParamError(\"recordID\");\n }\n // Do we have a publish status? If none, complain.\n String publish = params.publish\n if (StringUtils.isEmpty(publish)) {\n errors.missingParamError(\"publish\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" ArrayList<String> recordIdList = new ArrayList<String>();\n if (!StringUtils.isEmpty(recordId)) {\n recordIdList = paramsProcessorUtil.decodeIds(recordId);\n }",
" if (!meetingService.existsAnyRecording(recordIdList)) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find recordings\");\n return;\n // END - backward compatibility",
" }",
" meetingService.setPublishRecording(recordIdList, publish.toBoolean());\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><published>$publish</published></response>\", contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * DELETE_RECORDINGS API\n ******************************************************/\n def deleteRecordings = {\n String API_CALL = \"deleteRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.recordID)) {\n invalid(\"missingParamRecordID\", \"You must specify a recordID.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a recording id? If none, complain.\n String recordId = params.recordID\n if (StringUtils.isEmpty(recordId)) {\n errors.missingParamError(\"recordID\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" List<String> recordIdList = new ArrayList<String>();\n if (!StringUtils.isEmpty(recordId)) {\n recordIdList = paramsProcessorUtil.decodeIds(recordId);\n }",
" if (!meetingService.existsAnyRecording(recordIdList)) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find recordings\");\n return;\n // END - backward compatibility\n }",
" meetingService.deleteRecordings(recordIdList);\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><deleted>true</deleted></response>\", contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * UPDATE_RECORDINGS API\n ******************************************************/\n def updateRecordingsHandler = {\n String API_CALL = \"updateRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.recordID)) {\n invalid(\"missingParamRecordID\", \"You must specify a recordID.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a recording id? If none, complain.\n String recordId = params.recordID\n if (StringUtils.isEmpty(recordId)) {\n errors.missingParamError(\"recordID\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" List<String> recordIdList = new ArrayList<String>();\n if (!StringUtils.isEmpty(recordId)) {\n recordIdList = paramsProcessorUtil.decodeIds(recordId);\n }",
" if (!meetingService.existsAnyRecording(recordIdList)) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find recordings\");\n return;\n // END - backward compatibility\n }",
" //Execute code specific for this call\n Map<String, String> metaParams = ParamsProcessorUtil.processMetaParam(params)\n if (!metaParams.empty) {\n //Proceed with the update\n meetingService.updateRecordings(recordIdList, metaParams);\n }\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><updated>true</updated></response>\", contentType: \"text/xml\")\n }\n }\n }",
" def uploadDocuments(conf) { //\n log.debug(\"ApiController#uploadDocuments(${conf.getInternalId()})\");",
" String requestBody = request.inputStream == null ? null : request.inputStream.text;\n requestBody = StringUtils.isEmpty(requestBody) ? null : requestBody;",
" if (requestBody == null) {\n downloadAndProcessDocument(presentationService.defaultUploadedPresentation, conf.getInternalId(), true /* default presentation */, '');\n } else {\n def xml = new XmlSlurper().parseText(requestBody);\n xml.children().each { module ->\n log.debug(\"module config found: [${module.@name}]\");",
" if (\"presentation\".equals(module.@name.toString())) {\n // need to iterate over presentation files and process them\n Boolean current = true;\n module.children().each { document ->\n if (!StringUtils.isEmpty(document.@url.toString())) {\n def fileName;\n if (!StringUtils.isEmpty(document.@filename.toString())) {\n log.debug(\"user provided filename: [${module.@filename}]\");\n fileName = document.@filename.toString();\n }\n downloadAndProcessDocument(document.@url.toString(), conf.getInternalId(), current /* default presentation */, fileName);\n current = false;\n } else if (!StringUtils.isEmpty(document.@name.toString())) {\n def b64 = new Base64()\n def decodedBytes = b64.decode(document.text().getBytes())\n processDocumentFromRawBytes(decodedBytes, document.@name.toString(),\n conf.getInternalId(), current /* default presentation */);\n current = false;\n } else {\n log.debug(\"presentation module config found, but it did not contain url or name attributes\");\n }\n }\n }\n }\n }\n }",
" def processDocumentFromRawBytes(bytes, presOrigFilename, meetingId, current) {\n def uploadFailed = false\n def uploadFailReasons = new ArrayList<String>()",
" // Gets the name minus the path from a full fileName.\n // a/b/c.txt --> c.txt\n def presFilename = FilenameUtils.getName(presOrigFilename)\n def filenameExt = FilenameUtils.getExtension(presOrigFilename)\n def pres = null\n def presId = null",
" if (presFilename == \"\" || filenameExt == \"\") {\n log.debug(\"Upload failed. Invalid filename \" + presOrigFilename)\n uploadFailReasons.add(\"invalid_filename\")\n uploadFailed = true\n } else {\n String presentationDir = presentationService.getPresentationDir()\n presId = Util.generatePresentationId(presFilename)",
" File uploadDir = Util.createPresentationDir(meetingId, presentationDir, presId)\n if (uploadDir != null) {\n def newFilename = Util.createNewFilename(presId, filenameExt)\n pres = new File(uploadDir.absolutePath + File.separatorChar + newFilename);",
" FileOutputStream fos = new java.io.FileOutputStream(pres)\n fos.write(bytes)\n fos.flush()\n fos.close()\n } else {\n log.warn \"Upload failed. File Empty.\"\n uploadFailReasons.add(\"failed_to_download_file\")\n uploadFailed = true\n }\n }",
" // Hardcode pre-uploaded presentation to the default presentation window\n processUploadedFile(\"DEFAULT_PRESENTATION_POD\",\n meetingId,\n presId,\n presFilename,\n pres,\n current,\n \"preupload-raw-authz-token\",\n uploadFailed,\n uploadFailReasons)\n }",
" def downloadAndProcessDocument(address, meetingId, current, fileName) {\n log.debug(\"ApiController#downloadAndProcessDocument(${address}, ${meetingId}, ${fileName})\");\n String presOrigFilename;\n if (StringUtils.isEmpty(fileName)) {\n presOrigFilename = address.tokenize(\"/\")[-1];\n } else {\n presOrigFilename = fileName;\n }",
" def uploadFailed = false\n def uploadFailReasons = new ArrayList<String>()",
" // Gets the name minus the path from a full fileName.\n // a/b/c.txt --> c.txt\n def presFilename = FilenameUtils.getName(presOrigFilename)\n def filenameExt = FilenameUtils.getExtension(presOrigFilename)\n def pres = null\n def presId",
" if (presFilename == \"\" || filenameExt == \"\") {\n log.debug(\"Upload failed. Invalid filename \" + presOrigFilename)\n uploadFailReasons.add(\"invalid_filename\")\n uploadFailed = true\n } else {\n String presentationDir = presentationService.getPresentationDir()\n presId = Util.generatePresentationId(presFilename)\n File uploadDir = Util.createPresentationDir(meetingId, presentationDir, presId)\n if (uploadDir != null) {\n def newFilename = Util.createNewFilename(presId, filenameExt)\n def newFilePath = uploadDir.absolutePath + File.separatorChar + newFilename",
" if (presDownloadService.savePresentation(meetingId, newFilePath, address)) {\n pres = new File(newFilePath)\n } else {\n log.error(\"Failed to download presentation=[${address}], meeting=[${meetingId}], fileName=[${fileName}]\")\n uploadFailReasons.add(\"failed_to_download_file\")\n uploadFailed = true\n }\n }\n }",
" // Hardcode pre-uploaded presentation to the default presentation window\n processUploadedFile(\n \"DEFAULT_PRESENTATION_POD\",\n meetingId,\n presId,\n presFilename,\n pres,\n current,\n \"preupload-download-authz-token\",\n uploadFailed,\n uploadFailReasons\n )\n }",
"\n def processUploadedFile(podId, meetingId, presId, filename, presFile, current, authzToken, uploadFailed, uploadFailReasons ) {\n def presentationBaseUrl = presentationService.presentationBaseUrl\n // TODO add podId\n UploadedPresentation uploadedPres = new UploadedPresentation(podId,\n meetingId,\n presId,\n filename,\n presentationBaseUrl,\n current,\n authzToken,\n uploadFailed,\n uploadFailReasons)\n uploadedPres.setUploadedFile(presFile);\n presentationService.processUploadedPresentation(uploadedPres);\n }",
" def beforeInterceptor = {\n if (paramsProcessorUtil.isServiceEnabled() == false) {\n log.info(\"apiNotEnabled: The API service and/or controller is not enabled on this server. To use it, you must first enable it.\")\n // TODO: this doesn't stop the request - so it generates invalid XML\n // since the request continues and renders a second response\n invalid(\"apiNotEnabled\", \"The API service and/or controller is not enabled on this server. To use it, you must first enable it.\")\n }\n }",
" def respondWithConference(meeting, msgKey, msg) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n log.debug \"Rendering as xml\"\n render(text: responseBuilder.buildMeeting(meeting, msgKey, msg, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }",
" def getUserSession(token) {\n if (token == null) {\n return null\n }",
" UserSession us = meetingService.getUserSessionWithAuthToken(token)\n if (us == null) {\n log.info(\"Cannot find UserSession for token ${token}\")\n }",
" return us\n }",
" def sanitizeSessionToken(param) {\n if (param == null) {\n log.info(\"sanitizeSessionToken: token is null\")\n return null\n }",
" if (StringUtils.isEmpty(param)) {\n log.info(\"sanitizeSessionToken: token is empty\")\n return null\n }",
" return StringUtils.strip(param)\n }",
" private Boolean hasValidSession(token) {\n UserSession us = getUserSession(token)\n if (us == null) {\n return false\n }",
" if (!session[token]) {\n log.info(\"Session for token ${token} not found\")",
" Boolean allowRequestsWithoutSession = paramsProcessorUtil.getAllowRequestsWithoutSession()\n if (!allowRequestsWithoutSession) {\n log.info(\"Meeting related to ${token} doesn't allow requests without session\")\n return false\n }\n }",
" log.info(\"Token ${token} is valid\")\n return true\n }",
" // Validate maxParticipants constraint\n private Boolean hasReachedMaxParticipants(meeting, us) {\n // Meeting object calls it maxUsers to build up the drama\n int maxParticipants = meeting.getMaxUsers();\n // When is set to 0, the validation is ignored\n Boolean enabled = maxParticipants > 0;\n // Users refreshing page or reconnecting must be identified\n Boolean rejoin = meeting.getUserById(us.internalUserId) != null;\n // Users that passed enter once, still not joined but somehow re-entered\n Boolean reenter = meeting.getEnteredUserById(us.internalUserId) != null;\n // Users that already joined the meeting\n int joinedUsers = meeting.getUsers().size()\n // Users that are entering the meeting\n int enteredUsers = meeting.getEnteredUsers().size()",
" Boolean reachedMax = (joinedUsers + enteredUsers) >= maxParticipants;\n if (enabled && !rejoin && !reenter && reachedMax) {\n return true;\n }",
" return false;\n }",
" private void respondWithErrors(errorList, redirectResponse = false) {\n log.debug CONTROLLER_NAME + \"#invalid\"\n if (redirectResponse) {\n ArrayList<Object> errors = new ArrayList<Object>();\n errorList.getErrors().each { error ->\n Map<String, String> errorMap = new LinkedHashMap<String, String>()\n errorMap.put(\"key\", error[0])\n errorMap.put(\"message\", error[1])\n errors.add(errorMap)\n }",
" JSONArray errorsJSONArray = new JSONArray(errors);\n log.debug errorsJSONArray",
" respondWithRedirect(errorsJSONArray)\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildErrors(errorList.getErrors(), RESP_CODE_FAILED), contentType: \"text/xml\")\n }\n json {\n log.debug \"Rendering as json\"\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n messageKey key\n message msg\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" //TODO: method added for backward compatibility, it will be removed in next versions after 0.8\n private void invalid(key, msg, redirectResponse = false) {\n // Note: This xml scheme will be DEPRECATED.\n log.debug CONTROLLER_NAME + \"#invalid \" + msg\n if (redirectResponse) {\n ArrayList<Object> errors = new ArrayList<Object>();\n Map<String, String> errorMap = new LinkedHashMap<String, String>()\n errorMap.put(\"key\", key)\n errorMap.put(\"message\", msg)\n errors.add(errorMap)",
" JSONArray errorsJSONArray = new JSONArray(errors)\n log.debug \"JSON Errors {}\", errorsJSONArray.toString()",
" respondWithRedirect(errorsJSONArray)\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildError(key, msg, RESP_CODE_FAILED), contentType: \"text/xml\")\n }\n json {\n log.debug \"Rendering as json\"\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n messageKey key\n message msg\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" private void respondWithRedirect(errorsJSONArray) {\n String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()\n URI oldUri = URI.create(logoutUrl)",
" if (!StringUtils.isEmpty(params.logoutURL)) {\n try {\n oldUri = URI.create(params.logoutURL)\n } catch (Exception e) {\n // Do nothing, the variable oldUri was already initialized\n }\n }",
" String newQuery = oldUri.getQuery();",
" if (newQuery == null) {\n newQuery = \"errors=\"\n } else {\n newQuery += \"&\" + \"errors=\"\n }\n newQuery += errorsJSONArray",
" URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, oldUri.getFragment())",
" log.debug \"Constructed logout URL {}\", newUri.toString()\n redirect(url: newUri)\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,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [247], "buggy_code_start_loc": [247], "filenames": ["bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ApiController.groovy"], "fixing_code_end_loc": [250], "fixing_code_start_loc": [248], "message": "web/controllers/ApiController.groovy in BigBlueButton before 2.2.29 lacks certain parameter sanitization, as demonstrated by accepting control characters in a user name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bigbluebutton:bigbluebutton:*:*:*:*:*:*:*:*", "matchCriteriaId": "5FA0DCDA-3F90-4D22-A5A1-E6CD7861C2B8", "versionEndExcluding": "2.2.29", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "web/controllers/ApiController.groovy in BigBlueButton before 2.2.29 lacks certain parameter sanitization, as demonstrated by accepting control characters in a user name."}, {"lang": "es", "value": "web/controllers/ApiController.groovy en BigBlueButton versiones anteriores a 2.2.29 carece de cierta desinfecci\u00f3n de par\u00e1metros, como se demuestra al aceptar caracteres de control en un nombre de usuario"}], "evaluatorComment": null, "id": "CVE-2020-28954", "lastModified": "2020-11-29T23:41:06.973", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-11-19T22:15:13.757", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/commit/5c911ddeec4493f40f42e2f137800ed4692004a4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/commit/e59bcd0c33a6a3203c011faa8823ba2cac1e4f37"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/compare/v2.2.28...v2.2.29"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/issues/10818"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-116"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/bigbluebutton/bigbluebutton/commit/5c911ddeec4493f40f42e2f137800ed4692004a4"}, "type": "CWE-116"}
| 315
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/**\n ** BigBlueButton open source conferencing system - http://www.bigbluebutton.org/\n *\n * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below).\n *\n * This program is free software; you can redistribute it and/or modify it under the\n * terms of the GNU Lesser General Public License as published by the Free Software\n * Foundation; either version 3.0 of the License, or (at your option) any later\n * version.\n *\n * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License along\n * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>.\n *\n */\npackage org.bigbluebutton.web.controllers",
"import com.google.gson.Gson\nimport grails.web.context.ServletContextHolder\nimport groovy.json.JsonBuilder\nimport org.apache.commons.codec.binary.Base64\nimport org.apache.commons.io.FilenameUtils\nimport org.apache.commons.lang.RandomStringUtils\nimport org.apache.commons.lang.StringUtils\nimport org.bigbluebutton.api.*\nimport org.bigbluebutton.api.domain.Config\nimport org.bigbluebutton.api.domain.GuestPolicy\nimport org.bigbluebutton.api.domain.Meeting\nimport org.bigbluebutton.api.domain.UserSession\nimport org.bigbluebutton.api.util.ParamsUtil\nimport org.bigbluebutton.api.util.ResponseBuilder\nimport org.bigbluebutton.presentation.PresentationUrlDownloadService\nimport org.bigbluebutton.presentation.UploadedPresentation\nimport org.bigbluebutton.web.services.PresentationService\nimport org.bigbluebutton.web.services.turn.StunTurnService\nimport org.bigbluebutton.web.services.turn.TurnEntry\nimport org.bigbluebutton.web.services.turn.StunServer\nimport org.bigbluebutton.web.services.turn.RemoteIceCandidate\nimport org.json.JSONArray",
"import javax.servlet.ServletRequest",
"class ApiController {\n private static final Integer SESSION_TIMEOUT = 14400 // 4 hours\n private static final String CONTROLLER_NAME = 'ApiController'\n protected static final String RESP_CODE_SUCCESS = 'SUCCESS'\n protected static final String RESP_CODE_FAILED = 'FAILED'\n private static final String ROLE_MODERATOR = \"MODERATOR\"\n private static final String ROLE_ATTENDEE = \"VIEWER\"\n protected static Boolean REDIRECT_RESPONSE = true",
" MeetingService meetingService;\n PresentationService presentationService\n ParamsProcessorUtil paramsProcessorUtil\n ClientConfigService configService\n PresentationUrlDownloadService presDownloadService\n StunTurnService stunTurnService\n ResponseBuilder responseBuilder = initResponseBuilder()",
" def initResponseBuilder = {\n String protocol = this.getClass().getResource(\"\").getProtocol();\n if (Objects.equals(protocol, \"jar\")) {\n // Application running inside a JAR file\n responseBuilder = new ResponseBuilder(getClass().getClassLoader(), \"/WEB-INF/freemarker\")\n } else if (Objects.equals(protocol, \"file\")) {\n // Application unzipped and running outside a JAR file\n String templateLoc = ServletContextHolder.servletContext.getRealPath(\"/WEB-INF/freemarker\")\n // We should never have a null `templateLoc`\n responseBuilder = new ResponseBuilder(new File(templateLoc))\n }\n }",
" /* general methods */\n def index = {\n log.debug CONTROLLER_NAME + \"#index\"\n response.addHeader(\"Cache-Control\", \"no-cache\")",
" withFormat {\n xml {\n render(text: responseBuilder.buildMeetingVersion(paramsProcessorUtil.getApiVersion(), RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }",
" /***********************************\n * CREATE (API)\n ***********************************/\n def create = {\n String API_CALL = 'create'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"\n log.debug request.getParameterMap().toMapString()",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors();\n paramsProcessorUtil.processRequiredCreateParams(params, errors);",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree with the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" Meeting newMeeting = paramsProcessorUtil.processCreateParams(params)",
" if (meetingService.createMeeting(newMeeting)) {\n // See if the request came with pre-uploading of presentation.\n uploadDocuments(newMeeting); //\n respondWithConference(newMeeting, null, null)\n } else {\n // Translate the external meeting id into an internal meeting id.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID);\n Meeting existing = meetingService.getNotEndedMeetingWithId(internalMeetingId);\n if (existing != null) {\n log.debug \"Existing conference found\"\n Map<String, Object> updateParams = paramsProcessorUtil.processUpdateCreateParams(params);\n if (existing.getViewerPassword().equals(params.get(\"attendeePW\")) && existing.getModeratorPassword().equals(params.get(\"moderatorPW\"))) {\n //paramsProcessorUtil.updateMeeting(updateParams, existing);\n // trying to create a conference a second time, return success, but give extra info\n // Ignore pre-uploaded presentations. We only allow uploading of presentation once.\n //uploadDocuments(existing);\n respondWithConference(existing, \"duplicateWarning\", \"This conference was already in existence and may currently be in progress.\");\n } else {\n // BEGIN - backward compatibility\n invalid(\"idNotUnique\", \"A meeting already exists with that meeting ID. Please use a different meeting ID.\");\n return\n // END - backward compatibility",
" // enforce meetingID unique-ness\n errors.nonUniqueMeetingIdError()\n respondWithErrors(errors)\n }",
" return\n }\n }\n }",
"\n /**********************************************\n * JOIN API\n *********************************************/\n def join = {\n String API_CALL = 'join'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"\n ApiErrors errors = new ApiErrors()",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\", REDIRECT_RESPONSE)\n return\n }",
" //checking for an empty username or for a username containing whitespaces only\n if (!StringUtils.isEmpty(params.fullName)) {\n params.fullName = StringUtils.strip(params.fullName);\n if (StringUtils.isEmpty(params.fullName)) {\n invalid(\"missingParamFullName\", \"You must specify a name for the attendee who will be joining the meeting.\", REDIRECT_RESPONSE);\n return\n }\n } else {\n invalid(\"missingParamFullName\", \"You must specify a name for the attendee who will be joining the meeting.\", REDIRECT_RESPONSE);\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\", REDIRECT_RESPONSE)\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\", REDIRECT_RESPONSE)\n return\n }",
" if (StringUtils.isEmpty(params.password)) {\n invalid(\"invalidPassword\", \"You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference.\", REDIRECT_RESPONSE);\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\", REDIRECT_RESPONSE)\n return\n }",
" // END - backward compatibility",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" Boolean authenticated = false;",
" Boolean guest = false;\n if (!StringUtils.isEmpty(params.guest)) {\n guest = Boolean.parseBoolean(params.guest)\n } else {\n // guest param has not been passed. Make user as\n // authenticated by default. (ralam july 3, 2018)\n authenticated = true\n }",
"\n if (!StringUtils.isEmpty(params.auth)) {\n authenticated = Boolean.parseBoolean(params.auth)\n }",
" Boolean joinViaHtml5 = false;\n if (!StringUtils.isEmpty(params.joinViaHtml5)) {\n joinViaHtml5 = Boolean.parseBoolean(params.joinViaHtml5)\n }",
" // Do we have a name for the user joining? If none, complain.\n if (!StringUtils.isEmpty(params.fullName)) {\n params.fullName = StringUtils.strip(params.fullName);",
" // remove control characters ( sanitize )\n params.fullName = params.fullName.replaceAll(\"\\\\p{Cntrl}\", \"\");",
" if (StringUtils.isEmpty(params.fullName)) {\n errors.missingParamError(\"fullName\");\n }\n } else {\n errors.missingParamError(\"fullName\");\n }\n String fullName = ParamsUtil.stripHTMLTags(params.fullName)",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
" // Do we have a password? If not, complain.\n String attPW = params.password\n if (StringUtils.isEmpty(attPW)) {\n errors.missingParamError(\"password\");\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);",
" log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidMeetingIdentifier\", \"The meeting ID that you supplied did not match any existing meetings\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.invalidMeetingIdError();\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // the createTime mismatch with meeting's createTime, complain\n // In the future, the createTime param will be required\n if (params.createTime != null) {\n long createTime = 0;\n try {\n createTime = Long.parseLong(params.createTime);\n } catch (Exception e) {\n log.warn(\"could not parse createTime param\");\n createTime = -1;\n }\n if (createTime != meeting.getCreateTime()) {\n // BEGIN - backward compatibility\n invalid(\"mismatchCreateTimeParam\", \"The createTime parameter submitted mismatches with the current meeting.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.mismatchCreateTimeParam();\n respondWithErrors(errors, REDIRECT_RESPONSE);\n return\n }\n }",
" // Is this user joining a meeting that has been ended. If so, complain.\n if (meeting.isForciblyEnded()) {\n // BEGIN - backward compatibility\n invalid(\"meetingForciblyEnded\", \"You can not re-join a meeting that has already been forcibly ended. However, once the meeting is removed from memory (according to the timeout configured on this server, you will be able to once again create a meeting with the same meeting ID\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.meetingForciblyEndedError();\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // Now determine if this user is a moderator or a viewer.\n String role = null;\n if (meeting.getModeratorPassword().equals(attPW)) {\n role = Meeting.ROLE_MODERATOR\n } else if (meeting.getViewerPassword().equals(attPW)) {\n role = Meeting.ROLE_ATTENDEE\n }",
" if (role == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidPassword\", \"You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.invalidPasswordError()\n respondWithErrors(errors, REDIRECT_RESPONSE)\n return\n }",
" // We preprend \"w_\" to our internal meeting Id to indicate that this is a web user.\n // For users joining using the phone, we will prepend \"v_\" so it will be easier\n // to distinguish users who doesn't have a web client. (ralam june 12, 2017)\n String internalUserID = \"w_\" + RandomStringUtils.randomAlphanumeric(12).toLowerCase()",
" String authToken = RandomStringUtils.randomAlphanumeric(12).toLowerCase()",
" String sessionToken = RandomStringUtils.randomAlphanumeric(16).toLowerCase()",
" String externUserID = params.userID\n if (StringUtils.isEmpty(externUserID)) {\n externUserID = internalUserID\n }",
" //Return a Map with the user custom data\n Map<String, String> userCustomData = paramsProcessorUtil.getUserCustomData(params);",
" //Currently, it's associated with the externalUserID\n if (userCustomData.size() > 0)\n meetingService.addUserCustomData(meeting.getInternalId(), externUserID, userCustomData);",
" String configxml = null;",
" if (!StringUtils.isEmpty(params.configToken)) {\n Config conf = meeting.getConfig(params.configToken);\n if (conf == null) {\n // Check if this config is one of our pre-built config\n configxml = configService.getConfig(params.configToken)\n if (configxml == null) {\n // BEGIN - backward compatibility\n invalid(\"noConfigFound\", \"We could not find a config for this request.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.noConfigFound();\n respondWithErrors(errors);\n }\n } else {\n configxml = conf.config;\n }\n } else {\n Config conf = meeting.getDefaultConfig();\n configxml = conf.config;\n }",
" // Do not fail if there's no default config.xml, needed for an HTML5 client only scenario",
" String guestStatusVal = meeting.calcGuestStatus(role, guest, authenticated)",
" UserSession us = new UserSession();\n us.authToken = authToken;\n us.internalUserId = internalUserID\n us.conferencename = meeting.getName()\n us.meetingID = meeting.getInternalId()\n us.externMeetingID = meeting.getExternalId()\n us.externUserID = externUserID\n us.fullname = fullName\n us.role = role\n us.conference = meeting.getInternalId()\n us.room = meeting.getInternalId()\n us.voicebridge = meeting.getTelVoice()\n us.webvoiceconf = meeting.getWebVoice()\n us.mode = \"LIVE\"\n us.record = meeting.isRecord()\n us.welcome = meeting.getWelcomeMessage()\n us.guest = guest\n us.authed = authenticated\n us.guestStatus = guestStatusVal\n us.logoutUrl = meeting.getLogoutUrl()\n us.configXML = configxml;",
" if (!StringUtils.isEmpty(params.defaultLayout)) {\n us.defaultLayout = params.defaultLayout;\n }",
" if (!StringUtils.isEmpty(params.avatarURL)) {\n us.avatarURL = params.avatarURL;\n } else {\n us.avatarURL = meeting.defaultAvatarURL\n }",
" String meetingId = meeting.getInternalId()",
" if (hasReachedMaxParticipants(meeting, us)) {\n // BEGIN - backward compatibility\n invalid(\"maxParticipantsReached\", \"The number of participants allowed for this meeting has been reached.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.maxParticipantsReached();\n respondWithErrors(errors, REDIRECT_RESPONSE);\n return;\n }",
" // Register user into the meeting.\n meetingService.registerUser(\n us.meetingID,\n us.internalUserId,\n us.fullname,\n us.role,\n us.externUserID,\n us.authToken,\n us.avatarURL,\n us.guest,\n us.authed,\n guestStatusVal\n )",
" //Identify which of these to logs should be used. sessionToken or user-token\n log.info(\"Session sessionToken for \" + us.fullname + \" [\" + session[sessionToken] + \"]\")\n log.info(\"Session user-token for \" + us.fullname + \" [\" + session['user-token'] + \"]\")\n session.setMaxInactiveInterval(SESSION_TIMEOUT);",
" //check if exists the param redirect\n boolean redirectClient = true;\n String clientURL = paramsProcessorUtil.getDefaultClientUrl();",
" // server-wide configuration:\n // Depending on configuration, prefer the HTML5 client over Flash for moderators\n if (paramsProcessorUtil.getModeratorsJoinViaHTML5Client() && role == ROLE_MODERATOR) {\n joinViaHtml5 = true\n }",
" // Depending on configuration, prefer the HTML5 client over Flash for attendees\n if (paramsProcessorUtil.getAttendeesJoinViaHTML5Client() && role == ROLE_ATTENDEE) {\n joinViaHtml5 = true\n }",
" // single client join configuration:\n // Depending on configuration, prefer the HTML5 client over Flash client\n if (joinViaHtml5) {\n clientURL = paramsProcessorUtil.getHTML5ClientUrl();\n } else {\n if (!StringUtils.isEmpty(params.clientURL)) {\n clientURL = params.clientURL;\n }\n }",
" if (!StringUtils.isEmpty(params.redirect)) {\n try {\n redirectClient = Boolean.parseBoolean(params.redirect);\n } catch (Exception e) {\n redirectClient = true;\n }\n }",
" String msgKey = \"successfullyJoined\"\n String msgValue = \"You have joined successfully.\"",
" // Keep track of the client url in case this needs to wait for\n // approval as guest. We need to be able to send the user to the\n // client after being approved by moderator.\n us.clientUrl = clientURL + \"?sessionToken=\" + sessionToken",
" session[sessionToken] = sessionToken\n meetingService.addUserSession(sessionToken, us);",
" // Process if we send the user directly to the client or\n // have it wait for approval.\n String destUrl = clientURL + \"?sessionToken=\" + sessionToken\n if (guestStatusVal.equals(GuestPolicy.WAIT)) {\n String guestWaitUrl = paramsProcessorUtil.getDefaultGuestWaitURL();\n destUrl = guestWaitUrl + \"?sessionToken=\" + sessionToken\n msgKey = \"guestWait\"\n msgValue = \"Guest waiting for approval to join meeting.\"\n } else if (guestStatusVal.equals(GuestPolicy.DENY)) {\n destUrl = meeting.getLogoutUrl()\n msgKey = \"guestDeny\"\n msgValue = \"Guest denied to join meeting.\"\n }",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"join_api\");\n logData.put(\"description\", \"Handle JOIN API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" if (redirectClient) {\n log.info(\"Redirecting to ${destUrl}\");\n redirect(url: destUrl);\n } else {\n log.info(\"Successfully joined. Sending XML response.\");\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildJoinMeeting(us, session[sessionToken], guestStatusVal, destUrl, msgKey, msgValue, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /*******************************************\n * IS_MEETING_RUNNING API\n *******************************************/\n def isMeetingRunning = {\n String API_CALL = 'isMeetingRunning'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
"\n if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);\n log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n boolean isRunning = meeting != null && meeting.isRunning();",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(contentType: \"text/xml\") {\n render(text: responseBuilder.buildIsMeetingRunning(isRunning, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /************************************\n * END API\n ************************************/\n def end = {\n String API_CALL = \"end\"",
" log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (StringUtils.isEmpty(params.password)) {\n invalid(\"invalidPassword\", \"You must supply the moderator password for this call.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
" // Do we have a password? If not, complain.\n String modPW = params.password\n if (StringUtils.isEmpty(modPW)) {\n errors.missingParamError(\"password\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);\n log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find a meeting with that meeting ID - perhaps the meeting is not yet running?\");\n return;\n // END - backward compatibility",
" errors.invalidMeetingIdError();\n respondWithErrors(errors)\n return;\n }",
" if (meeting.getModeratorPassword().equals(modPW) == false) {\n // BEGIN - backward compatibility\n invalid(\"invalidPassword\", \"You must supply the moderator password for this call.\");\n return;\n // END - backward compatibility",
" errors.invalidPasswordError();\n respondWithErrors(errors)\n return;\n }",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", meeting.getInternalId());\n logData.put(\"extMeetingid\", meeting.getExternalId());\n logData.put(\"name\", meeting.getName());\n logData.put(\"logCode\", \"end_api\");\n logData.put(\"description\", \"Handle END API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" meetingService.endMeeting(meeting.getInternalId());",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(contentType: \"text/xml\") {\n render(text: responseBuilder.buildEndRunning(\"sentEndMeetingRequest\", \"A request to end the meeting was sent. Please wait a few seconds, and then use the getMeetingInfo or isMeetingRunning API calls to verify that it was ended.\", RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /*****************************************\n * GETMEETINGINFO API\n *****************************************/\n def getMeetingInfo = {\n String API_CALL = \"getMeetingInfo\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a meeting id? If none, complain.\n if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n errors.missingParamError(\"meetingID\");\n }\n } else {\n errors.missingParamError(\"meetingID\");\n }\n String externalMeetingId = params.meetingID",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" // Everything is good so far. Translate the external meeting id to an internal meeting id. If\n // we can't find the meeting, complain.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId);\n log.info(\"Retrieving meeting ${internalMeetingId}\")\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find a meeting with that meeting ID\");\n return;\n // END - backward compatibility",
" errors.invalidMeetingIdError();\n respondWithErrors(errors)\n return;\n }",
" withFormat {\n xml {\n render(text: responseBuilder.buildGetMeetingInfoResponse(meeting, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }",
" /************************************\n * GETMEETINGS API\n ************************************/\n def getMeetingsHandler = {\n String API_CALL = \"getMeetings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" Collection<Meeting> mtgs = meetingService.getMeetings();",
" if (mtgs == null || mtgs.isEmpty()) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildGetMeetingsResponse(mtgs, \"noMeetings\", \"no meetings were found on this server\", RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")",
" withFormat {\n xml {\n render(text: responseBuilder.buildGetMeetingsResponse(mtgs, null, null, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }",
" /************************************\n * GETSESSIONS API\n ************************************/\n def getSessionsHandler = {\n String API_CALL = \"getSessions\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" Collection<UserSession> sssns = meetingService.getSessions();",
" if (sssns == null || sssns.isEmpty()) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildGetSessionsResponse(sssns, \"noSessions\", \"no sessions were found on this serverr\", RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(contentType: \"text/xml\") {\n render(text: responseBuilder.buildGetSessionsResponse(sssns, null, null, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }\n }\n }",
"\n private static Map<String, String[]> getParameters(ServletRequest request) {\n // Copy the parameters into our own Map as we can't pass the paramMap\n // from the request as it's an unmodifiable map.\n Map<String, String[]> reqParams = new HashMap<String, String[]>();\n Map<String, String[]> unModReqParams = request.getParameterMap();",
" SortedSet<String> keys = new TreeSet<String>(unModReqParams.keySet());",
" for(String key : keys) {\n reqParams.put(key, unModReqParams.get(key));\n }",
" return reqParams;\n }",
" /***********************************************\n * POLL API\n ***********************************************/\n def setPollXML = {\n String API_CALL = \"setPollXML\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.pollXML)) {\n invalid(\"configXMLError\", \"You did not pass a poll XML\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" // Translate the external meeting id into an internal meeting id.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID);\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidMeetingIdentifier\", \"The meeting ID that you supplied did not match any existing meetings\");\n return;\n // END - backward compatibility\n }",
" Map<String, String[]> reqParams = getParameters(request)",
" String pollXML = params.pollXML",
" String decodedPollXML;",
" try {\n decodedPollXML = URLDecoder.decode(pollXML, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n log.error \"Couldn't decode poll XML.\", e\n invalid(\"pollXMLError\", \"Cannot decode poll XML\")\n return;\n }",
" if (!paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n invalid(\"pollXMLChecksumError\", \"pollXMLChecksumError: request did not pass the checksum security check.\")\n }\n }\n } else {\n def pollxml = new XmlSlurper().parseText(decodedPollXML);",
" pollxml.children().each { poll ->\n String title = poll.title.text();\n String question = poll.question.text();\n String questionType = poll.questionType.text();",
" ArrayList<String> answers = new ArrayList<String>();\n poll.answers.children().each { answer ->\n answers.add(answer.text());\n }",
" //send poll to BigBlueButton Apps\n meetingService.createdPolls(meeting.getInternalId(), title, question, questionType, answers);\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode></response>\", contentType: \"text/xml\")\n }\n }\n }\n }",
" /***********************************************\n * CONFIG API\n ***********************************************/\n def setConfigXML = {\n String API_CALL = \"setConfigXML\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.configXML)) {\n invalid(\"configXMLError\", \"You did not pass a config XML\")\n return\n }",
" if (!StringUtils.isEmpty(params.meetingID)) {\n params.meetingID = StringUtils.strip(params.meetingID);\n if (StringUtils.isEmpty(params.meetingID)) {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }\n } else {\n invalid(\"missingParamMeetingID\", \"You must specify a meeting ID for the meeting.\");\n return\n }",
" // Translate the external meeting id into an internal meeting id.\n String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID);\n Meeting meeting = meetingService.getMeeting(internalMeetingId);\n if (meeting == null) {\n // BEGIN - backward compatibility\n invalid(\"invalidMeetingIdentifier\", \"The meeting ID that you supplied did not match any existing meetings\");\n return;\n // END - backward compatibility\n }",
" Map<String, String[]> reqParams = getParameters(request)",
" String configXML = params.configXML",
" String decodedConfigXML;",
" try {\n decodedConfigXML = URLDecoder.decode(configXML, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n log.error(\"Couldn't decode config XML.\");\n invalid(\"configXMLError\", \"Cannot decode config XML\")\n return;\n }",
" if (!paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n invalid(\"configXMLChecksumError\", \"configXMLChecksumError: request did not pass the checksum security check.\")\n }\n }\n } else {\n boolean defaultConfig = false;",
" if (!StringUtils.isEmpty(params.defaultConfig)) {\n try {\n defaultConfig = Boolean.parseBoolean(params.defaultConfig);\n } catch (Exception e) {\n defaultConfig = false;\n }\n }",
" String token = meeting.storeConfig(defaultConfig, decodedConfigXML);\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><configToken>$token</configToken></response>\", contentType: \"text/xml\")\n }\n }\n }\n }",
" def getDefaultConfigXML = {",
" String API_CALL = \"getDefaultConfigXML\"\n ApiErrors errors = new ApiErrors();",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
"\n // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" String defConfigXML = paramsProcessorUtil.getDefaultConfigXML();\n if (StringUtils.isEmpty(defConfigXML)) {\n // BEGIN - backward compatibility\n invalid(\"noConfigFound\", \"We could not find a config for this request.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.noConfigFound();\n respondWithErrors(errors);\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n render text: defConfigXML, contentType: 'text/xml'\n }",
" def configXML = {\n String API_CALL = 'configXML'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()\n boolean reject = false\n String sessionToken = sanitizeSessionToken(params.sessionToken)\n if (!hasValidSession(sessionToken)) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildConfgXmlReject(\"Could not find conference.\", logoutUrl, RESP_CODE_FAILED), contentType: \"text/xml\")\n }\n }\n } else {\n UserSession us = getUserSession(sessionToken)\n if (StringUtils.isEmpty(us.configXML)) {\n // BEGIN - backward compatibility\n invalid(\"noConfigFound\", \"We could not find a config for this request.\", REDIRECT_RESPONSE);\n return\n // END - backward compatibility",
" errors.noConfigFound();\n respondWithErrors(errors);\n }",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingId\", us.meetingID);\n logData.put(\"externalMeetingId\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userId\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"handle_configxml_api\");\n logData.put(\"description\", \"Handling ConfigXml API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n render text: us.configXML, contentType: 'text/xml'\n }\n }",
" /**********************************************\n * GUEST WAIT API\n *********************************************/\n def guestWaitHandler = {\n String API_CALL = 'guestWait'\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"\n ApiErrors errors = new ApiErrors()\n boolean reject = false;\n String sessionToken = sanitizeSessionToken(params.sessionToken)",
" UserSession us = getUserSession(sessionToken);\n Meeting meeting = null;",
" if (us == null) {\n log.debug(\"No user with session token.\")\n reject = true;\n } else {\n meeting = meetingService.getMeeting(us.meetingID);\n if (meeting == null || meeting.isForciblyEnded()) {\n log.debug(\"Meeting not found.\")\n reject = true\n }\n }",
" // Determine the logout url so we can send the user there.\n String logoutUrl = us != null ? us.logoutUrl : paramsProcessorUtil.getDefaultLogoutUrl()",
" if (reject) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n message \"Could not process waiting guest.\"\n logoutURL logoutUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n } else {\n //check if exists the param redirect\n boolean redirectClient = true;",
" // Get the client url we stored in the join api call before\n // being told to wait.\n String clientURL = us.clientUrl;\n log.info(\"clientURL = \" + clientURL)\n log.info(\"redirect = .\" + redirectClient)\n if (!StringUtils.isEmpty(params.redirect)) {\n try {\n redirectClient = Boolean.parseBoolean(params.redirect);\n log.info(\"redirect 2 = .\" + redirectClient)\n } catch (Exception e) {\n redirectClient = true;\n }\n }",
" // The client url is ovewriten. Let's allow it.\n if (!StringUtils.isEmpty(params.clientURL)) {\n clientURL = params.clientURL;\n }",
" String guestWaitStatus = us.guestStatus",
" log.debug(\"GuestWaitStatus = \" + guestWaitStatus)",
" String msgKey = \"guestAllowed\"\n String msgValue = \"Guest allowed to join meeting.\"",
" String destUrl = clientURL\n log.debug(\"destUrl = \" + destUrl)",
"\n if (guestWaitStatus.equals(GuestPolicy.WAIT)) {\n clientURL = paramsProcessorUtil.getDefaultGuestWaitURL();\n destUrl = clientURL + \"?sessionToken=\" + sessionToken\n log.debug(\"GuestPolicy.WAIT - destUrl = \" + destUrl)\n msgKey = \"guestWait\"\n msgValue = \"Guest waiting for approval to join meeting.\"\n // We force the response to not do a redirect. Otherwise,\n // the client would just be redirecting into this endpoint.\n redirectClient = false",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"guest_wait\");\n logData.put(\"description\", \"Guest waiting for approval.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" } else if (guestWaitStatus.equals(GuestPolicy.DENY)) {\n destUrl = meeting.getLogoutUrl()\n msgKey = \"guestDenied\"\n msgValue = \"Guest denied to join meeting.\"",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"guest_denied\");\n logData.put(\"description\", \"Guest denied.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);\n }",
" if (redirectClient) {\n log.info(\"Redirecting to ${destUrl}\");\n redirect(url: destUrl);\n } else {\n log.info(\"Successfully joined. Sending XML response.\");\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_SUCCESS\n messageKey msgKey\n message msgValue\n meeting_id us.meetingID\n user_id us.internalUserId\n auth_token us.authToken\n session_token session[sessionToken]\n guestStatus guestWaitStatus\n url destUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }\n }",
" /***********************************************\n * ENTER API\n ***********************************************/\n def enter = {\n boolean reject = false;",
" String sessionToken = sanitizeSessionToken(params.sessionToken)\n UserSession us = getUserSession(sessionToken);\n Meeting meeting = null;",
" String respMessage = \"Session \" + sessionToken + \" not found.\"",
" if (!hasValidSession(sessionToken)) {\n reject = true;\n } else {\n meeting = meetingService.getMeeting(us.meetingID);\n if (meeting == null || meeting.isForciblyEnded()) {\n reject = true\n respMessage = \"Meeting not found or ended for session \" + sessionToken + \".\"\n } else {\n if (hasReachedMaxParticipants(meeting, us)) {\n reject = true;\n respMessage = \"The number of participants allowed for this meeting has been reached.\";\n } else {\n meeting.userEntered(us.internalUserId);\n }\n }\n if (us.guestStatus.equals(GuestPolicy.DENY)) {\n respMessage = \"User denied for user with session \" + sessionToken + \".\"\n reject = true\n }\n }",
" if (reject) {\n // Determine the logout url so we can send the user there.\n String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()",
" if (us != null) {\n logoutUrl = us.logoutUrl\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n message respMessage\n logoutURL logoutUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n } else {",
" Map<String, String> userCustomData = paramsProcessorUtil.getUserCustomData(params);",
" // Generate a new userId for this user. This prevents old connections from\n // removing the user when the user reconnects after being disconnected. (ralam jan 22, 2015)\n // We use underscore (_) to associate userid with the user. We are also able to track\n // how many times a user reconnects or refresh the browser.\n String newInternalUserID = us.internalUserId //+ \"_\" + us.incrementConnectionNum()",
" Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", newInternalUserID);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"logCode\", \"handle_enter_api\");\n logData.put(\"description\", \"Handling ENTER API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);",
" log.info(\" --analytics-- data=\" + logStr);",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_SUCCESS\n fullname us.fullname\n confname us.conferencename\n meetingID us.meetingID\n externMeetingID us.externMeetingID\n externUserID us.externUserID\n internalUserID newInternalUserID\n authToken us.authToken\n role us.role\n guest us.guest\n guestStatus us.guestStatus\n conference us.conference\n room us.room\n voicebridge us.voicebridge\n dialnumber meeting.getDialNumber()\n webvoiceconf us.webvoiceconf\n mode us.mode\n record us.record\n isBreakout meeting.isBreakout()\n logoutTimer meeting.getLogoutTimer()\n allowStartStopRecording meeting.getAllowStartStopRecording()\n welcome us.welcome\n if (!StringUtils.isEmpty(meeting.moderatorOnlyMessage) && us.role.equals(ROLE_MODERATOR)) {\n modOnlyMessage meeting.moderatorOnlyMessage\n }\n if (!StringUtils.isEmpty(meeting.bannerText)) {\n bannerText meeting.getBannerText()\n bannerColor meeting.getBannerColor()\n }\n customLogoURL meeting.getCustomLogoURL()\n customCopyright meeting.getCustomCopyright()\n muteOnStart meeting.getMuteOnStart()\n allowModsToUnmuteUsers meeting.getAllowModsToUnmuteUsers()\n logoutUrl us.logoutUrl\n defaultLayout us.defaultLayout\n avatarURL us.avatarURL\n if (meeting.breakoutRoomsParams != null) {\n breakoutRooms {\n enabled meeting.breakoutRoomsParams.enabled\n record meeting.breakoutRoomsParams.record\n privateChatEnabled meeting.breakoutRoomsParams.privateChatEnabled\n }\n }\n customdata (\n meeting.getUserCustomData(us.externUserID).collect { k, v ->\n [\"$k\": v]\n }\n )\n metadata (\n meeting.getMetadata().collect { k, v ->\n [\"$k\": v]\n }\n )\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" /***********************************************\n * STUN/TURN API\n ***********************************************/\n def stuns = {\n boolean reject = false;",
" String sessionToken = sanitizeSessionToken(params.sessionToken)\n UserSession us = getUserSession(sessionToken);\n Meeting meeting = null;",
" if (!hasValidSession(sessionToken)) {\n reject = true;\n } else {\n meeting = meetingService.getMeeting(us.meetingID);\n if (meeting == null || meeting.isForciblyEnded()) {\n reject = true\n }\n }",
" if (reject) {\n String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder {\n returncode RESP_CODE_FAILED\n message \"Could not find conference.\"\n logoutURL logoutUrl\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n } else {\n Set<StunServer> stuns = stunTurnService.getStunServers()\n Set<TurnEntry> turns = stunTurnService.getStunAndTurnServersFor(us.internalUserId)\n Set<RemoteIceCandidate> candidates = stunTurnService.getRemoteIceCandidates()",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n json {\n def builder = new JsonBuilder()\n builder {\n stunServers (\n stuns.collect { stun ->\n [url: stun.url]\n }\n )\n turnServers (\n turns.collect { turn ->\n [\n username: turn.username,\n password: turn.password,\n url: turn.url,\n ttl: turn.ttl\n ]\n }\n )\n remoteIceCandidates (\n candidates.collect { candidate ->\n [ip: candidate.ip ]\n }\n )\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" /*************************************************\n * SIGNOUT API\n *************************************************/\n def signOut = {",
" String sessionToken = sanitizeSessionToken(params.sessionToken)",
" Meeting meeting = null;",
" if (sessionToken != null) {",
" UserSession us = meetingService.removeUserSessionWithAuthToken(sessionToken);\n if (us != null) {\n Map<String, Object> logData = new HashMap<String, Object>();\n logData.put(\"meetingid\", us.meetingID);\n logData.put(\"extMeetingid\", us.externMeetingID);\n logData.put(\"name\", us.fullname);\n logData.put(\"userid\", us.internalUserId);\n logData.put(\"sessionToken\", sessionToken);\n logData.put(\"message\", \"handle_signout_api\");\n logData.put(\"logCode\", \"signout_api\");\n logData.put(\"description\", \"Handling SIGNOUT API.\");",
" Gson gson = new Gson();\n String logStr = gson.toJson(logData);\n log.info(\" --analytics-- data=\" + logStr);\n } else {\n log.info(\"Could not find user session for session token {}\", sessionToken)\n }",
"\n session.removeAttribute(sessionToken)\n }",
" response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode></response>\", contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * GET_RECORDINGS API\n ******************************************************/\n def getRecordingsHandler = {\n String API_CALL = \"getRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n respondWithErrors(errors)\n return\n }",
" log.debug request.getQueryString()",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" List<String> externalMeetingIds = new ArrayList<String>();\n if (!StringUtils.isEmpty(params.meetingID)) {\n externalMeetingIds = paramsProcessorUtil.decodeIds(params.meetingID);\n }",
" ArrayList<String> internalRecordIds = new ArrayList<String>()\n if (!StringUtils.isEmpty(params.recordID)) {\n internalRecordIds = paramsProcessorUtil.decodeIds(params.recordID)\n }",
" ArrayList<String> states = new ArrayList<String>()\n if (!StringUtils.isEmpty(params.state)) {\n states = paramsProcessorUtil.decodeIds(params.state)\n }",
" // Everything is good so far.\n if (internalRecordIds.size() == 0 && externalMeetingIds.size() > 0) {\n // No recordIDs, process the request based on meetingID(s)\n // Translate the external meeting ids to internal meeting ids (which is the seed for the recordIDs).\n internalRecordIds = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingIds);\n }",
" for(String intRecId : internalRecordIds) {\n log.debug intRecId\n }",
" Map<String, String> metadataFilters = ParamsProcessorUtil.processMetaParam(params);",
" def getRecordingsResult = meetingService.getRecordings2x(internalRecordIds, states, metadataFilters)",
" withFormat {\n xml {\n render(text: getRecordingsResult, contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * PUBLISH_RECORDINGS API\n ******************************************************/\n def publishRecordings = {\n String API_CALL = \"publishRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.recordID)) {\n invalid(\"missingParamRecordID\", \"You must specify a recordID.\");\n return\n }",
" if (StringUtils.isEmpty(params.publish)) {\n invalid(\"missingParamPublish\", \"You must specify a publish value true or false.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a recording id? If none, complain.\n String recordId = params.recordID\n if (StringUtils.isEmpty(recordId)) {\n errors.missingParamError(\"recordID\");\n }\n // Do we have a publish status? If none, complain.\n String publish = params.publish\n if (StringUtils.isEmpty(publish)) {\n errors.missingParamError(\"publish\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" ArrayList<String> recordIdList = new ArrayList<String>();\n if (!StringUtils.isEmpty(recordId)) {\n recordIdList = paramsProcessorUtil.decodeIds(recordId);\n }",
" if (!meetingService.existsAnyRecording(recordIdList)) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find recordings\");\n return;\n // END - backward compatibility",
" }",
" meetingService.setPublishRecording(recordIdList, publish.toBoolean());\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><published>$publish</published></response>\", contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * DELETE_RECORDINGS API\n ******************************************************/\n def deleteRecordings = {\n String API_CALL = \"deleteRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.recordID)) {\n invalid(\"missingParamRecordID\", \"You must specify a recordID.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a recording id? If none, complain.\n String recordId = params.recordID\n if (StringUtils.isEmpty(recordId)) {\n errors.missingParamError(\"recordID\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" List<String> recordIdList = new ArrayList<String>();\n if (!StringUtils.isEmpty(recordId)) {\n recordIdList = paramsProcessorUtil.decodeIds(recordId);\n }",
" if (!meetingService.existsAnyRecording(recordIdList)) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find recordings\");\n return;\n // END - backward compatibility\n }",
" meetingService.deleteRecordings(recordIdList);\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><deleted>true</deleted></response>\", contentType: \"text/xml\")\n }\n }\n }",
" /******************************************************\n * UPDATE_RECORDINGS API\n ******************************************************/\n def updateRecordingsHandler = {\n String API_CALL = \"updateRecordings\"\n log.debug CONTROLLER_NAME + \"#${API_CALL}\"",
" // BEGIN - backward compatibility\n if (StringUtils.isEmpty(params.checksum)) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }",
" if (StringUtils.isEmpty(params.recordID)) {\n invalid(\"missingParamRecordID\", \"You must specify a recordID.\");\n return\n }",
" if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n invalid(\"checksumError\", \"You did not pass the checksum security check\")\n return\n }\n // END - backward compatibility",
" ApiErrors errors = new ApiErrors()",
" // Do we have a checksum? If none, complain.\n if (StringUtils.isEmpty(params.checksum)) {\n errors.missingParamError(\"checksum\");\n }",
" // Do we have a recording id? If none, complain.\n String recordId = params.recordID\n if (StringUtils.isEmpty(recordId)) {\n errors.missingParamError(\"recordID\");\n }",
" if (errors.hasErrors()) {\n respondWithErrors(errors)\n return\n }",
" // Do we agree on the checksum? If not, complain.\n if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) {\n errors.checksumError()\n respondWithErrors(errors)\n return\n }",
" List<String> recordIdList = new ArrayList<String>();\n if (!StringUtils.isEmpty(recordId)) {\n recordIdList = paramsProcessorUtil.decodeIds(recordId);\n }",
" if (!meetingService.existsAnyRecording(recordIdList)) {\n // BEGIN - backward compatibility\n invalid(\"notFound\", \"We could not find recordings\");\n return;\n // END - backward compatibility\n }",
" //Execute code specific for this call\n Map<String, String> metaParams = ParamsProcessorUtil.processMetaParam(params)\n if (!metaParams.empty) {\n //Proceed with the update\n meetingService.updateRecordings(recordIdList, metaParams);\n }\n withFormat {\n xml {\n // No need to use the response builder here until we have a more complex response\n render(text: \"<response><returncode>$RESP_CODE_SUCCESS</returncode><updated>true</updated></response>\", contentType: \"text/xml\")\n }\n }\n }",
" def uploadDocuments(conf) { //\n log.debug(\"ApiController#uploadDocuments(${conf.getInternalId()})\");",
" String requestBody = request.inputStream == null ? null : request.inputStream.text;\n requestBody = StringUtils.isEmpty(requestBody) ? null : requestBody;",
" if (requestBody == null) {\n downloadAndProcessDocument(presentationService.defaultUploadedPresentation, conf.getInternalId(), true /* default presentation */, '');\n } else {\n def xml = new XmlSlurper().parseText(requestBody);\n xml.children().each { module ->\n log.debug(\"module config found: [${module.@name}]\");",
" if (\"presentation\".equals(module.@name.toString())) {\n // need to iterate over presentation files and process them\n Boolean current = true;\n module.children().each { document ->\n if (!StringUtils.isEmpty(document.@url.toString())) {\n def fileName;\n if (!StringUtils.isEmpty(document.@filename.toString())) {\n log.debug(\"user provided filename: [${module.@filename}]\");\n fileName = document.@filename.toString();\n }\n downloadAndProcessDocument(document.@url.toString(), conf.getInternalId(), current /* default presentation */, fileName);\n current = false;\n } else if (!StringUtils.isEmpty(document.@name.toString())) {\n def b64 = new Base64()\n def decodedBytes = b64.decode(document.text().getBytes())\n processDocumentFromRawBytes(decodedBytes, document.@name.toString(),\n conf.getInternalId(), current /* default presentation */);\n current = false;\n } else {\n log.debug(\"presentation module config found, but it did not contain url or name attributes\");\n }\n }\n }\n }\n }\n }",
" def processDocumentFromRawBytes(bytes, presOrigFilename, meetingId, current) {\n def uploadFailed = false\n def uploadFailReasons = new ArrayList<String>()",
" // Gets the name minus the path from a full fileName.\n // a/b/c.txt --> c.txt\n def presFilename = FilenameUtils.getName(presOrigFilename)\n def filenameExt = FilenameUtils.getExtension(presOrigFilename)\n def pres = null\n def presId = null",
" if (presFilename == \"\" || filenameExt == \"\") {\n log.debug(\"Upload failed. Invalid filename \" + presOrigFilename)\n uploadFailReasons.add(\"invalid_filename\")\n uploadFailed = true\n } else {\n String presentationDir = presentationService.getPresentationDir()\n presId = Util.generatePresentationId(presFilename)",
" File uploadDir = Util.createPresentationDir(meetingId, presentationDir, presId)\n if (uploadDir != null) {\n def newFilename = Util.createNewFilename(presId, filenameExt)\n pres = new File(uploadDir.absolutePath + File.separatorChar + newFilename);",
" FileOutputStream fos = new java.io.FileOutputStream(pres)\n fos.write(bytes)\n fos.flush()\n fos.close()\n } else {\n log.warn \"Upload failed. File Empty.\"\n uploadFailReasons.add(\"failed_to_download_file\")\n uploadFailed = true\n }\n }",
" // Hardcode pre-uploaded presentation to the default presentation window\n processUploadedFile(\"DEFAULT_PRESENTATION_POD\",\n meetingId,\n presId,\n presFilename,\n pres,\n current,\n \"preupload-raw-authz-token\",\n uploadFailed,\n uploadFailReasons)\n }",
" def downloadAndProcessDocument(address, meetingId, current, fileName) {\n log.debug(\"ApiController#downloadAndProcessDocument(${address}, ${meetingId}, ${fileName})\");\n String presOrigFilename;\n if (StringUtils.isEmpty(fileName)) {\n presOrigFilename = address.tokenize(\"/\")[-1];\n } else {\n presOrigFilename = fileName;\n }",
" def uploadFailed = false\n def uploadFailReasons = new ArrayList<String>()",
" // Gets the name minus the path from a full fileName.\n // a/b/c.txt --> c.txt\n def presFilename = FilenameUtils.getName(presOrigFilename)\n def filenameExt = FilenameUtils.getExtension(presOrigFilename)\n def pres = null\n def presId",
" if (presFilename == \"\" || filenameExt == \"\") {\n log.debug(\"Upload failed. Invalid filename \" + presOrigFilename)\n uploadFailReasons.add(\"invalid_filename\")\n uploadFailed = true\n } else {\n String presentationDir = presentationService.getPresentationDir()\n presId = Util.generatePresentationId(presFilename)\n File uploadDir = Util.createPresentationDir(meetingId, presentationDir, presId)\n if (uploadDir != null) {\n def newFilename = Util.createNewFilename(presId, filenameExt)\n def newFilePath = uploadDir.absolutePath + File.separatorChar + newFilename",
" if (presDownloadService.savePresentation(meetingId, newFilePath, address)) {\n pres = new File(newFilePath)\n } else {\n log.error(\"Failed to download presentation=[${address}], meeting=[${meetingId}], fileName=[${fileName}]\")\n uploadFailReasons.add(\"failed_to_download_file\")\n uploadFailed = true\n }\n }\n }",
" // Hardcode pre-uploaded presentation to the default presentation window\n processUploadedFile(\n \"DEFAULT_PRESENTATION_POD\",\n meetingId,\n presId,\n presFilename,\n pres,\n current,\n \"preupload-download-authz-token\",\n uploadFailed,\n uploadFailReasons\n )\n }",
"\n def processUploadedFile(podId, meetingId, presId, filename, presFile, current, authzToken, uploadFailed, uploadFailReasons ) {\n def presentationBaseUrl = presentationService.presentationBaseUrl\n // TODO add podId\n UploadedPresentation uploadedPres = new UploadedPresentation(podId,\n meetingId,\n presId,\n filename,\n presentationBaseUrl,\n current,\n authzToken,\n uploadFailed,\n uploadFailReasons)\n uploadedPres.setUploadedFile(presFile);\n presentationService.processUploadedPresentation(uploadedPres);\n }",
" def beforeInterceptor = {\n if (paramsProcessorUtil.isServiceEnabled() == false) {\n log.info(\"apiNotEnabled: The API service and/or controller is not enabled on this server. To use it, you must first enable it.\")\n // TODO: this doesn't stop the request - so it generates invalid XML\n // since the request continues and renders a second response\n invalid(\"apiNotEnabled\", \"The API service and/or controller is not enabled on this server. To use it, you must first enable it.\")\n }\n }",
" def respondWithConference(meeting, msgKey, msg) {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n log.debug \"Rendering as xml\"\n render(text: responseBuilder.buildMeeting(meeting, msgKey, msg, RESP_CODE_SUCCESS), contentType: \"text/xml\")\n }\n }\n }",
" def getUserSession(token) {\n if (token == null) {\n return null\n }",
" UserSession us = meetingService.getUserSessionWithAuthToken(token)\n if (us == null) {\n log.info(\"Cannot find UserSession for token ${token}\")\n }",
" return us\n }",
" def sanitizeSessionToken(param) {\n if (param == null) {\n log.info(\"sanitizeSessionToken: token is null\")\n return null\n }",
" if (StringUtils.isEmpty(param)) {\n log.info(\"sanitizeSessionToken: token is empty\")\n return null\n }",
" return StringUtils.strip(param)\n }",
" private Boolean hasValidSession(token) {\n UserSession us = getUserSession(token)\n if (us == null) {\n return false\n }",
" if (!session[token]) {\n log.info(\"Session for token ${token} not found\")",
" Boolean allowRequestsWithoutSession = paramsProcessorUtil.getAllowRequestsWithoutSession()\n if (!allowRequestsWithoutSession) {\n log.info(\"Meeting related to ${token} doesn't allow requests without session\")\n return false\n }\n }",
" log.info(\"Token ${token} is valid\")\n return true\n }",
" // Validate maxParticipants constraint\n private Boolean hasReachedMaxParticipants(meeting, us) {\n // Meeting object calls it maxUsers to build up the drama\n int maxParticipants = meeting.getMaxUsers();\n // When is set to 0, the validation is ignored\n Boolean enabled = maxParticipants > 0;\n // Users refreshing page or reconnecting must be identified\n Boolean rejoin = meeting.getUserById(us.internalUserId) != null;\n // Users that passed enter once, still not joined but somehow re-entered\n Boolean reenter = meeting.getEnteredUserById(us.internalUserId) != null;\n // Users that already joined the meeting\n int joinedUsers = meeting.getUsers().size()\n // Users that are entering the meeting\n int enteredUsers = meeting.getEnteredUsers().size()",
" Boolean reachedMax = (joinedUsers + enteredUsers) >= maxParticipants;\n if (enabled && !rejoin && !reenter && reachedMax) {\n return true;\n }",
" return false;\n }",
" private void respondWithErrors(errorList, redirectResponse = false) {\n log.debug CONTROLLER_NAME + \"#invalid\"\n if (redirectResponse) {\n ArrayList<Object> errors = new ArrayList<Object>();\n errorList.getErrors().each { error ->\n Map<String, String> errorMap = new LinkedHashMap<String, String>()\n errorMap.put(\"key\", error[0])\n errorMap.put(\"message\", error[1])\n errors.add(errorMap)\n }",
" JSONArray errorsJSONArray = new JSONArray(errors);\n log.debug errorsJSONArray",
" respondWithRedirect(errorsJSONArray)\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildErrors(errorList.getErrors(), RESP_CODE_FAILED), contentType: \"text/xml\")\n }\n json {\n log.debug \"Rendering as json\"\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n messageKey key\n message msg\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" //TODO: method added for backward compatibility, it will be removed in next versions after 0.8\n private void invalid(key, msg, redirectResponse = false) {\n // Note: This xml scheme will be DEPRECATED.\n log.debug CONTROLLER_NAME + \"#invalid \" + msg\n if (redirectResponse) {\n ArrayList<Object> errors = new ArrayList<Object>();\n Map<String, String> errorMap = new LinkedHashMap<String, String>()\n errorMap.put(\"key\", key)\n errorMap.put(\"message\", msg)\n errors.add(errorMap)",
" JSONArray errorsJSONArray = new JSONArray(errors)\n log.debug \"JSON Errors {}\", errorsJSONArray.toString()",
" respondWithRedirect(errorsJSONArray)\n } else {\n response.addHeader(\"Cache-Control\", \"no-cache\")\n withFormat {\n xml {\n render(text: responseBuilder.buildError(key, msg, RESP_CODE_FAILED), contentType: \"text/xml\")\n }\n json {\n log.debug \"Rendering as json\"\n def builder = new JsonBuilder()\n builder.response {\n returncode RESP_CODE_FAILED\n messageKey key\n message msg\n }\n render(contentType: \"application/json\", text: builder.toPrettyString())\n }\n }\n }\n }",
" private void respondWithRedirect(errorsJSONArray) {\n String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl()\n URI oldUri = URI.create(logoutUrl)",
" if (!StringUtils.isEmpty(params.logoutURL)) {\n try {\n oldUri = URI.create(params.logoutURL)\n } catch (Exception e) {\n // Do nothing, the variable oldUri was already initialized\n }\n }",
" String newQuery = oldUri.getQuery();",
" if (newQuery == null) {\n newQuery = \"errors=\"\n } else {\n newQuery += \"&\" + \"errors=\"\n }\n newQuery += errorsJSONArray",
" URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, oldUri.getFragment())",
" log.debug \"Constructed logout URL {}\", newUri.toString()\n redirect(url: newUri)\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [247], "buggy_code_start_loc": [247], "filenames": ["bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ApiController.groovy"], "fixing_code_end_loc": [250], "fixing_code_start_loc": [248], "message": "web/controllers/ApiController.groovy in BigBlueButton before 2.2.29 lacks certain parameter sanitization, as demonstrated by accepting control characters in a user name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:bigbluebutton:bigbluebutton:*:*:*:*:*:*:*:*", "matchCriteriaId": "5FA0DCDA-3F90-4D22-A5A1-E6CD7861C2B8", "versionEndExcluding": "2.2.29", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "web/controllers/ApiController.groovy in BigBlueButton before 2.2.29 lacks certain parameter sanitization, as demonstrated by accepting control characters in a user name."}, {"lang": "es", "value": "web/controllers/ApiController.groovy en BigBlueButton versiones anteriores a 2.2.29 carece de cierta desinfecci\u00f3n de par\u00e1metros, como se demuestra al aceptar caracteres de control en un nombre de usuario"}], "evaluatorComment": null, "id": "CVE-2020-28954", "lastModified": "2020-11-29T23:41:06.973", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/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": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-11-19T22:15:13.757", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/commit/5c911ddeec4493f40f42e2f137800ed4692004a4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/commit/e59bcd0c33a6a3203c011faa8823ba2cac1e4f37"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/compare/v2.2.28...v2.2.29"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/bigbluebutton/bigbluebutton/issues/10818"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-116"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/bigbluebutton/bigbluebutton/commit/5c911ddeec4493f40f42e2f137800ed4692004a4"}, "type": "CWE-116"}
| 315
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# Gerapy",
"\n\n\n[](https://github.com/Gerapy/Gerapy/stargazers)\n\n\n",
"",
"> 注:从 Gerapy 2.x 开始,其定位发生改变,不再支持 Scrapyd,转而支持 Docker、Kubernetes 的部署,另外开发还会迁移到 Scrapy 可视化配置和智能解析方面,敬请期待。",
"\nDistributed Crawler Management Framework Based on Scrapy, Scrapyd, Scrapyd-Client, Scrapyd-API, Django and Vue.js.",
"## Documentation",
"Documentation is available online at [https://docs.gerapy.com/](https://docs.gerapy.com/) and [https://github.com/Gerapy/Docs](https://github.com/Gerapy/Docs).",
"## Support",
"Gerapy is developed based on Python 3.x. Python 2.x may be supported later.",
"## Usage",
"Install Gerapy by pip:",
"```bash\npip3 install gerapy\n```",
"After the installation, you need to do these things below to run Gerapy server:",
"If you have installed Gerapy successfully, you can use command `gerapy`. If not, check the installation.",
"First use this command to initialize the workspace:",
"```bash\ngerapy init\n```",
"Now you will get a folder named `gerapy`. Also you can specify the name of your workspace by this command:",
"```\ngerapy init <workspace>\n```",
"Then `cd` to this folder, and run this command to initialize the Database:",
"```bash\ncd gerapy\ngerapy migrate\n```",
"Next you need to create a superuser by this command:",
"```\ngerapy createsuperuser\n```",
"Then you can runserver by this command:",
"```bash\ngerapy runserver\n```",
"Then you can visit [http://localhost:8000](http://localhost:8000) to enjoy it. Also you can vist [http://localhost:8000/admin](http://localhost:8000/admin) to get the admin management backend.",
"If you want to run Gerapy in public, just run like this:",
"```\ngerapy runserver 0.0.0.0:8000\n```",
"Then it will run with public host and port 8000.",
"In Gerapy, You can create a configurable project and then configure and generate code of Scrapy automatically. But this module is unstable, we're trying to refine it.",
"Also you can drag your Scrapy Project to `projects` folder. Then refresh web, it will appear in the Project Index Page and comes to un-configurable, but you can edit this project through the web page.",
"As for deployment, you can move to Deploy Page. Firstly you need to build your project and add client in the Client Index Page, then you can deploy the project just by clicking button.",
"After the deployment, you can manage the job in Monitor Page.",
"## Docker",
"Just run this command:",
"```\ndocker run -d -v ~/gerapy:/app/gerapy -p 8000:8000 germey/gerapy\n```",
"Then it will run at port 8000. You can use the temp admin account (username: admin, password: admin) to login. And please change the password later for safety.",
"Command Usage:",
"```\ndocker run -d -v <workspace>:/app/gerapy -p <public_port>:<container_port> germey/gerapy\n```",
"Please specify your workspace to mount Gerapy workspace by `-v <workspace>:/app/gerapy` and specify server port by `-p <public_port>:<container_port>`.",
"If you run Gerapy by Docker, you can visit Gerapy website such as [http://localhost:8000](http://localhost:8000) and enjoy it, no need to do other initialzation things.",
"## TodoList",
"- [x] Add Visual Configuration of Spider with Previewing Website\n- [x] Add Scrapyd Auth Management\n- [x] Add Gerapy Auth Management\n- [x] Add Timed Task Scheduler\n- [ ] Add Visual Configuration of Scrapy\n- [ ] Add Intelligent Analysis of Web Page",
"## Communication",
"If you have any questions or ideas, you can send [Issues](https://github.com/Gerapy/Gerapy/issues) or [Pull Requests](https://github.com/Gerapy/Gerapy/pulls), your suggestions are really import for us, thanks for your contirbution."
] |
[
1,
1,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"# Gerapy",
"\n\n\n[](https://github.com/Gerapy/Gerapy/stargazers)\n\n\n",
"",
"\nDistributed Crawler Management Framework Based on Scrapy, Scrapyd, Scrapyd-Client, Scrapyd-API, Django and Vue.js.",
"## Documentation",
"Documentation is available online at [https://docs.gerapy.com/](https://docs.gerapy.com/) and [https://github.com/Gerapy/Docs](https://github.com/Gerapy/Docs).",
"## Support",
"Gerapy is developed based on Python 3.x. Python 2.x may be supported later.",
"## Usage",
"Install Gerapy by pip:",
"```bash\npip3 install gerapy\n```",
"After the installation, you need to do these things below to run Gerapy server:",
"If you have installed Gerapy successfully, you can use command `gerapy`. If not, check the installation.",
"First use this command to initialize the workspace:",
"```bash\ngerapy init\n```",
"Now you will get a folder named `gerapy`. Also you can specify the name of your workspace by this command:",
"```\ngerapy init <workspace>\n```",
"Then `cd` to this folder, and run this command to initialize the Database:",
"```bash\ncd gerapy\ngerapy migrate\n```",
"Next you need to create a superuser by this command:",
"```\ngerapy createsuperuser\n```",
"Then you can runserver by this command:",
"```bash\ngerapy runserver\n```",
"Then you can visit [http://localhost:8000](http://localhost:8000) to enjoy it. Also you can vist [http://localhost:8000/admin](http://localhost:8000/admin) to get the admin management backend.",
"If you want to run Gerapy in public, just run like this:",
"```\ngerapy runserver 0.0.0.0:8000\n```",
"Then it will run with public host and port 8000.",
"In Gerapy, You can create a configurable project and then configure and generate code of Scrapy automatically. But this module is unstable, we're trying to refine it.",
"Also you can drag your Scrapy Project to `projects` folder. Then refresh web, it will appear in the Project Index Page and comes to un-configurable, but you can edit this project through the web page.",
"As for deployment, you can move to Deploy Page. Firstly you need to build your project and add client in the Client Index Page, then you can deploy the project just by clicking button.",
"After the deployment, you can manage the job in Monitor Page.",
"## Docker",
"Just run this command:",
"```\ndocker run -d -v ~/gerapy:/app/gerapy -p 8000:8000 germey/gerapy\n```",
"Then it will run at port 8000. You can use the temp admin account (username: admin, password: admin) to login. And please change the password later for safety.",
"Command Usage:",
"```\ndocker run -d -v <workspace>:/app/gerapy -p <public_port>:<container_port> germey/gerapy\n```",
"Please specify your workspace to mount Gerapy workspace by `-v <workspace>:/app/gerapy` and specify server port by `-p <public_port>:<container_port>`.",
"If you run Gerapy by Docker, you can visit Gerapy website such as [http://localhost:8000](http://localhost:8000) and enjoy it, no need to do other initialzation things.",
"## TodoList",
"- [x] Add Visual Configuration of Spider with Previewing Website\n- [x] Add Scrapyd Auth Management\n- [x] Add Gerapy Auth Management\n- [x] Add Timed Task Scheduler\n- [ ] Add Visual Configuration of Scrapy\n- [ ] Add Intelligent Analysis of Web Page",
"## Communication",
"If you have any questions or ideas, you can send [Issues](https://github.com/Gerapy/Gerapy/issues) or [Pull Requests](https://github.com/Gerapy/Gerapy/pulls), your suggestions are really import for us, thanks for your contirbution."
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"VERSION = (0, 9, '3a3')",
"\n__version__ = '.'.join(map(str, VERSION))",
"version = lambda: __version__"
] |
[
0,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"VERSION = (0, 9, '3b1')",
"\n__version__ = '.'.join(map(str, VERSION))",
"version = lambda: __version__"
] |
[
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"",
"from pathlib import Path\nfrom urllib.parse import unquote\nimport base64\nimport json, os, requests, time, pytz, pymongo\nfrom shutil import rmtree\nfrom requests.exceptions import ConnectionError\nfrom os.path import join, exists\nfrom django.shortcuts import render\nfrom django.core.serializers import serialize\nfrom django.http import HttpResponse\nfrom django.forms.models import model_to_dict\nfrom django.utils import timezone\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom subprocess import Popen, PIPE\nfrom gerapy import get_logger\nfrom gerapy.server.core.response import JsonResponse\nfrom gerapy.cmd.init import PROJECTS_FOLDER\nfrom gerapy.server.server.settings import TIME_ZONE\nfrom gerapy.server.core.models import Client, Project, Deploy, Monitor, Task\nfrom gerapy.server.core.build import build_project, find_egg\nfrom gerapy.server.core.utils import IGNORES, scrapyd_url, log_url, get_tree, get_scrapyd, process_html, bytes2str, \\\n clients_of_task, get_job_id\nfrom django_apscheduler.models import DjangoJob, DjangoJobExecution\nfrom django.core.files.storage import FileSystemStorage\nimport zipfile",
"logger = get_logger(__name__)",
"\n@api_view(['GET'])\n# @permission_classes([IsAuthenticated])\ndef index(request):\n \"\"\"\n render index page\n :param request: request object\n :return: page\n \"\"\"\n return render(request, 'index.html')",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef index_status(request):\n \"\"\"\n index statistics\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'GET':\n clients = Client.objects.all()\n data = {\n 'success': 0,\n 'error': 0,\n 'project': 0,\n }\n # clients info\n for client in clients:\n try:\n requests.get(scrapyd_url(client.ip, client.port), timeout=1)\n data['success'] += 1\n except ConnectionError:\n data['error'] += 1\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n files = os.listdir(path)\n # projects info\n for file in files:\n if os.path.isdir(join(path, file)) and not file in IGNORES:\n data['project'] += 1\n return JsonResponse(data)",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef client_index(request):\n \"\"\"\n get client list\n :param request: request object\n :return: client list\n \"\"\"\n return HttpResponse(serialize('json', Client.objects.order_by('-id')))",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef client_info(request, client_id):\n \"\"\"\n get client info\n :param request: request object\n :param id: client id\n :return: json\n \"\"\"\n if request.method == 'GET':\n return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef client_status(request, client_id):\n \"\"\"\n get client status\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'GET':\n # get client object\n client = Client.objects.get(id=client_id)\n requests.get(scrapyd_url(client.ip, client.port), timeout=3)\n return JsonResponse({'result': '1'})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef client_update(request, client_id):\n \"\"\"\n update client info\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'POST':\n client = Client.objects.filter(id=client_id)\n data = json.loads(request.body)\n client.update(**data)\n return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef client_create(request):\n \"\"\"\n create a client\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n client = Client.objects.create(**data)\n return JsonResponse(model_to_dict(client))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef client_remove(request, client_id):\n \"\"\"\n remove a client\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'POST':\n client = Client.objects.get(id=client_id)\n # delete deploy\n Deploy.objects.filter(client=client).delete()\n # delete client\n Client.objects.filter(id=client_id).delete()\n return JsonResponse({'result': '1'})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef spider_list(request, client_id, project_name):\n \"\"\"\n get spider list from one client\n :param request: request Object\n :param client_id: client id\n :param project_name: project name\n :return: json\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)\n spiders = scrapyd.list_spiders(project_name)\n spiders = [{'name': spider, 'id': index + 1} for index, spider in enumerate(spiders)]\n return JsonResponse(spiders)",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef spider_start(request, client_id, project_name, spider_name):\n \"\"\"\n start a spider\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param spider_name: spider name\n :return: json\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)\n job = scrapyd.schedule(project_name, spider_name)\n return JsonResponse({'job': job})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_list(request, client_id):\n \"\"\"\n project deployed list on one client\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)\n projects = scrapyd.list_projects()\n return JsonResponse(projects)",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_index(request):\n \"\"\"\n project index list\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'GET':\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n files = os.listdir(path)\n project_list = []\n for file in files:\n if os.path.isdir(join(path, file)) and not file in IGNORES:\n project_list.append({'name': file})\n return JsonResponse(project_list)",
"\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef project_configure(request, project_name):\n \"\"\"\n get configuration\n :param request: request object\n :param project_name: project name\n :return: json\n \"\"\"\n # get configuration\n if request.method == 'GET':\n project = Project.objects.get(name=project_name)\n project = model_to_dict(project)\n project['configuration'] = json.loads(project['configuration']) if project['configuration'] else None\n return JsonResponse(project)\n \n # update configuration\n elif request.method == 'POST':\n project = Project.objects.filter(name=project_name)\n data = json.loads(request.body)\n configuration = json.dumps(data.get('configuration'), ensure_ascii=False)\n project.update(**{'configuration': configuration})\n ",
"",
" # execute generate cmd\n cmd = ' '.join(['gerapy', 'generate', project_name])\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n \n if not stderr:\n return JsonResponse({'status': '1'})\n else:\n return JsonResponse({'status': '0', 'message': stderr})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_tree(request, project_name):\n \"\"\"\n get file tree of project\n :param request: request object\n :param project_name: project name\n :return: json of tree\n \"\"\"\n if request.method == 'GET':\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n # get tree data\n tree = get_tree(join(path, project_name))\n return JsonResponse(tree)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_create(request):\n \"\"\"\n create a configurable project\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n data['configurable'] = 1\n project, result = Project.objects.update_or_create(**data)\n # generate a single project folder\n path = join(os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER)), data['name'])\n os.mkdir(path)\n return JsonResponse(model_to_dict(project))",
"\n@api_view(['POST'])\n# @permission_classes([IsAuthenticated])\ndef project_upload(request):\n \"\"\"\n upload project\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n file = request.FILES['file']\n file_name = file.name\n fs = FileSystemStorage(PROJECTS_FOLDER)\n zip_file_name = fs.save(file_name, file)\n logger.debug('zip file name %s', zip_file_name)\n # extract zip file\n with zipfile.ZipFile(join(PROJECTS_FOLDER, zip_file_name), 'r') as zip_ref:\n zip_ref.extractall(PROJECTS_FOLDER)\n logger.debug('extracted files to %s', PROJECTS_FOLDER)\n return JsonResponse({'status': True})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_clone(request):\n \"\"\"\n clone project from github\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n address = data.get('address')\n if not address.startswith('http'):\n return JsonResponse({'status': False})\n address = address + '.git' if not address.endswith('.git') else address\n cmd = 'git clone {address} {target}'.format(address=address, target=join(PROJECTS_FOLDER, Path(address).stem))\n logger.debug('clone cmd %s', cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n logger.debug('clone run result %s', stdout)\n if stderr: logger.error(stderr)\n return JsonResponse({'status': True}) if not stderr else JsonResponse({'status': False})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_remove(request, project_name):\n \"\"\"\n remove project from disk and db\n :param request: request object\n :param project_name: project name\n :return: result of remove\n \"\"\"\n if request.method == 'POST':\n # delete deployments\n project = Project.objects.get(name=project_name)\n Deploy.objects.filter(project=project).delete()\n # delete project\n result = Project.objects.filter(name=project_name).delete()\n # get project path\n path = join(os.path.abspath(os.getcwd()), PROJECTS_FOLDER)\n project_path = join(path, project_name)\n # delete project file tree\n if exists(project_path):\n rmtree(project_path)\n return JsonResponse({'result': result})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_version(request, client_id, project_name):\n \"\"\"\n get project deploy version\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :return: deploy version of project\n \"\"\"\n if request.method == 'GET':\n # get client and project model\n client = Client.objects.get(id=client_id)\n project = Project.objects.get(name=project_name)\n scrapyd = get_scrapyd(client)\n # if deploy info exists in db, return it\n if Deploy.objects.filter(client=client, project=project):\n deploy = Deploy.objects.get(client=client, project=project)\n # if deploy info does not exists in db, create deploy info\n else:\n try:\n versions = scrapyd.list_versions(project_name)\n except ConnectionError:\n return JsonResponse({'message': 'Connect Error'}, status=500)\n if len(versions) > 0:\n version = versions[-1]\n deployed_at = timezone.datetime.fromtimestamp(int(version), tz=pytz.timezone(TIME_ZONE))\n else:\n deployed_at = None\n deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at)\n # return deploy json info\n return JsonResponse(model_to_dict(deploy))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_deploy(request, client_id, project_name):\n \"\"\"\n deploy project operation\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :return: json of deploy result\n \"\"\"\n if request.method == 'POST':\n # get project folder\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n project_path = join(path, project_name)\n # find egg file\n egg = find_egg(project_path)\n if not egg:\n return JsonResponse({'message': 'egg not found'}, status=500)\n egg_file = open(join(project_path, egg), 'rb')\n # get client and project model\n client = Client.objects.get(id=client_id)\n project = Project.objects.get(name=project_name)\n # execute deploy operation\n scrapyd = get_scrapyd(client)\n scrapyd.add_version(project_name, int(time.time()), egg_file.read())\n # update deploy info\n deployed_at = timezone.now()\n Deploy.objects.filter(client=client, project=project).delete()\n deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at,\n description=project.description)\n return JsonResponse(model_to_dict(deploy))",
"\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef project_build(request, project_name):\n \"\"\"\n get build info or execute build operation\n :param request: request object\n :param project_name: project name\n :return: json\n \"\"\"\n # get project folder\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n project_path = join(path, project_name)\n \n # get build version\n if request.method == 'GET':\n egg = find_egg(project_path)\n # if built, save or update project to db\n if egg:\n built_at = timezone.datetime.fromtimestamp(os.path.getmtime(join(project_path, egg)),\n tz=pytz.timezone(TIME_ZONE))\n if not Project.objects.filter(name=project_name):\n Project(name=project_name, built_at=built_at, egg=egg).save()\n model = Project.objects.get(name=project_name)\n else:\n model = Project.objects.get(name=project_name)\n model.built_at = built_at\n model.egg = egg\n model.save()\n # if not built, just save project name to db\n else:\n if not Project.objects.filter(name=project_name):\n Project(name=project_name).save()\n model = Project.objects.get(name=project_name)\n # transfer model to dict then dumps it to json\n data = model_to_dict(model)\n return JsonResponse(data)\n \n # build operation manually by clicking button\n elif request.method == 'POST':\n data = json.loads(request.body)\n description = data['description']\n build_project(project_name)\n egg = find_egg(project_path)\n if not egg:\n return JsonResponse({'message': 'egg not found'}, status=500)\n # update built_at info\n built_at = timezone.now()\n # if project does not exists in db, create it\n if not Project.objects.filter(name=project_name):\n Project(name=project_name, description=description, built_at=built_at, egg=egg).save()\n model = Project.objects.get(name=project_name)\n # if project exists, update egg, description, built_at info\n else:\n model = Project.objects.get(name=project_name)\n model.built_at = built_at\n model.egg = egg\n model.description = description\n model.save()\n # transfer model to dict then dumps it to json\n data = model_to_dict(model)\n return JsonResponse(data)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_parse(request, project_name):\n \"\"\"\n parse project\n :param request: request object\n :param project_name: project name\n :return: requests, items, response\n \"\"\"\n if request.method == 'POST':\n project_path = join(PROJECTS_FOLDER, project_name)\n data = json.loads(request.body)\n logger.debug('post data %s', data)\n spider_name = data.get('spider')\n args = {\n 'start': data.get('start', False),\n 'method': data.get('method', 'GET'),\n 'url': data.get('url'),\n 'callback': data.get('callback'),\n 'cookies': \"'\" + json.dumps(data.get('cookies', {}), ensure_ascii=False) + \"'\",\n 'headers': \"'\" + json.dumps(data.get('headers', {}), ensure_ascii=False) + \"'\",\n 'meta': \"'\" + json.dumps(data.get('meta', {}), ensure_ascii=False) + \"'\",\n 'dont_filter': data.get('dont_filter', False),\n 'priority': data.get('priority', 0),\n }\n # set request body\n body = data.get('body', '')\n if args.get('method').lower() != 'get':\n args['body'] = \"'\" + json.dumps(body, ensure_ascii=False) + \"'\"\n \n args_cmd = ' '.join(\n ['--{arg} {value}'.format(arg=arg, value=value) for arg, value in args.items()])\n logger.debug('args cmd %s', args_cmd)\n cmd = 'gerapy parse {args_cmd} {project_path} {spider_name}'.format(\n args_cmd=args_cmd,\n project_path=project_path,\n spider_name=spider_name\n )\n logger.debug('parse cmd %s', cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n logger.debug('stdout %s, stderr %s', stdout, stderr)\n if not stderr:\n return JsonResponse({'status': True, 'result': json.loads(stdout)})\n else:\n return JsonResponse({'status': False, 'message': stderr})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_read(request):\n \"\"\"\n get content of project file\n :param request: request object\n :return: file content\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['label'])\n # binary file\n with open(path, 'rb') as f:\n return HttpResponse(f.read().decode('utf-8'))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_update(request):\n \"\"\"\n update project file\n :param request: request object\n :return: result of update\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['label'])\n code = data['code']\n with open(path, 'w', encoding='utf-8') as f:\n f.write(code)\n return JsonResponse({'result': '1'})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_create(request):\n \"\"\"\n create project file\n :param request: request object\n :return: result of create\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['name'])\n open(path, 'w', encoding='utf-8').close()\n return JsonResponse({'result': '1'})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_delete(request):\n \"\"\"\n delete project file\n :param request: request object\n :return: result of delete\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['label'])\n result = os.remove(path)\n return JsonResponse({'result': result})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_rename(request):\n \"\"\"\n rename file name\n :param request: request object\n :return: result of rename\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n pre = join(data['path'], data['pre'])\n new = join(data['path'], data['new'])\n os.rename(pre, new)\n return JsonResponse({'result': '1'})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef job_list(request, client_id, project_name):\n \"\"\"\n get job list of project from one client\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :return: list of jobs\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)",
" try:\n result = scrapyd.list_jobs(project_name)\n jobs = []\n statuses = ['pending', 'running', 'finished']\n for status in statuses:\n for job in result.get(status):\n job['status'] = status\n jobs.append(job)\n return JsonResponse(jobs)\n except ConnectionError:\n return JsonResponse({'message': 'Connect Error'}, status=500)",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef job_log(request, client_id, project_name, spider_name, job_id):\n \"\"\"\n get log of jog\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param spider_name: spider name\n :param job_id: job id\n :return: log of job\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n # get log url\n url = log_url(client.ip, client.port, project_name, spider_name, job_id)",
" try:\n # get last 1000 bytes of log\n response = requests.get(url, timeout=5, headers={\n 'Range': 'bytes=-1000'\n }, auth=(client.username, client.password) if client.auth else None)\n # Get encoding\n encoding = response.apparent_encoding\n # log not found\n if response.status_code == 404:\n return JsonResponse({'message': 'Log Not Found'}, status=404)\n # bytes to string\n text = response.content.decode(encoding, errors='replace')\n return HttpResponse(text)\n except requests.ConnectionError:\n return JsonResponse({'message': 'Load Log Error'}, status=500)",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef job_cancel(request, client_id, project_name, job_id):\n \"\"\"\n cancel a job\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param job_id: job id\n :return: json of cancel\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)",
" try:\n scrapyd = get_scrapyd(client)\n result = scrapyd.cancel(project_name, job_id)\n return JsonResponse(result)\n except ConnectionError:\n return JsonResponse({'message': 'Connect Error'})",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef del_version(request, client_id, project, version):\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)",
" try:\n scrapyd = get_scrapyd(client)\n result = scrapyd.delete_version(project=project, version=version)\n return JsonResponse(result)\n except ConnectionError:\n return JsonResponse({'message': 'Connect Error'})",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef del_project(request, client_id, project):\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)",
" try:\n scrapyd = get_scrapyd(client)\n result = scrapyd.delete_project(project=project)\n return JsonResponse(result)\n except ConnectionError:\n return JsonResponse({'message': 'Connect Error'})",
"",
"@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef monitor_db_list(request):\n \"\"\"\n get monitor db list\n :param request: request object\n :return: json of db list\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n url = data['url']\n type = data['type']\n if type == 'MongoDB':\n client = pymongo.MongoClient(url)\n dbs = client.list_database_names()\n return JsonResponse(dbs)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef monitor_collection_list(request):\n \"\"\"\n get monitor collection list\n :param request: request object\n :return: json of collection list\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n url = data['url']\n db = data['db']\n type = data['type']\n if type == 'MongoDB':\n client = pymongo.MongoClient(url)\n db = client[db]\n collections = db.collection_names()\n return JsonResponse(collections)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef monitor_create(request):\n \"\"\"\n create a monitor\n :param request: request object\n :return: json of create\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n data = data['form']\n data['configuration'] = json.dumps(data['configuration'], ensure_ascii=False)\n monitor = Monitor.objects.create(**data)\n return JsonResponse(model_to_dict(monitor))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef task_create(request):\n \"\"\"\n add task\n :param request: request object\n :return: Bool\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n task = Task.objects.create(clients=json.dumps(data.get('clients'), ensure_ascii=False),\n project=data.get('project'),\n name=data.get('name'),\n spider=data.get('spider'),\n trigger=data.get('trigger'),\n configuration=json.dumps(data.get('configuration'), ensure_ascii=False),\n modified=1)\n return JsonResponse({'result': '1', 'data': model_to_dict(task)})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef task_update(request, task_id):\n \"\"\"\n update task info\n :param request: request object\n :param task_id: task id\n :return: json\n \"\"\"\n if request.method == 'POST':\n task = Task.objects.filter(id=task_id)\n data = json.loads(request.body)\n data['clients'] = json.dumps(data.get('clients'), ensure_ascii=False)\n data['configuration'] = json.dumps(data.get('configuration'), ensure_ascii=False)\n data['modified'] = 1\n task.update(**data)\n return JsonResponse(model_to_dict(Task.objects.get(id=task_id)))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef task_remove(request, task_id):\n \"\"\"\n remove task by task_id\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':",
" try:\n # delete job from DjangoJob\n task = Task.objects.get(id=task_id)\n clients = clients_of_task(task)\n for client in clients:\n job_id = get_job_id(client, task)\n DjangoJob.objects.filter(name=job_id).delete()\n # delete task\n Task.objects.filter(id=task_id).delete()\n return JsonResponse({'result': '1'})\n except:\n return JsonResponse({'result': '0'})",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef task_info(request, task_id):\n \"\"\"\n get task info\n :param request: request object\n :param task_id: task id\n :return: json\n \"\"\"\n if request.method == 'GET':\n task = Task.objects.get(id=task_id)\n data = model_to_dict(task)\n data['clients'] = json.loads(data.get('clients'))\n data['configuration'] = json.loads(data.get('configuration'))\n return JsonResponse({'data': data})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef task_index(request):\n \"\"\"\n get all tasks\n :param request:\n :return:\n \"\"\"\n if request.method == 'GET':\n tasks = Task.objects.values()\n return JsonResponse({'result': '1', 'data': tasks})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef task_status(request, task_id):\n \"\"\"\n get task status info\n :param request: request object\n :param task_id: task id\n :return:\n \"\"\"\n if request.method == 'GET':\n result = []\n task = Task.objects.get(id=task_id)\n clients = clients_of_task(task)\n for client in clients:\n job_id = get_job_id(client, task)\n jobs = DjangoJob.objects.filter(name=job_id)\n logger.debug('jobs from djangojob %s', jobs)\n # if job does not exist, for date mode exceed time\n if not jobs: continue\n job = DjangoJob.objects.get(name=job_id)\n executions = serialize('json', DjangoJobExecution.objects.filter(job=job))\n result.append({\n 'client': model_to_dict(client),\n 'next': job.next_run_time,\n 'executions': json.loads(executions)\n })\n return JsonResponse({'data': result})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef render_html(request):\n \"\"\"\n render html with url\n :param request:\n :return:\n \"\"\"\n if request.method == 'GET':\n url = request.GET.get('url')\n url = unquote(base64.b64decode(url).decode('utf-8'))\n js = request.GET.get('js', 0)\n script = request.GET.get('script')",
" try:\n response = requests.get(url, timeout=5)\n response.encoding = response.apparent_encoding\n html = process_html(response.text)\n return HttpResponse(html)\n except Exception as e:\n return JsonResponse({'message': e.args}, status=500)"
] |
[
0,
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,
0,
1,
1,
0,
1,
1,
0,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
0
] |
PreciseBugs
|
{"buggy_code_end_loc": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"import re",
"from pathlib import Path\nfrom urllib.parse import unquote\nimport base64\nimport json, os, requests, time, pytz, pymongo\nfrom shutil import rmtree\nfrom requests.exceptions import ConnectionError\nfrom os.path import join, exists\nfrom django.shortcuts import render\nfrom django.core.serializers import serialize\nfrom django.http import HttpResponse\nfrom django.forms.models import model_to_dict\nfrom django.utils import timezone\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom subprocess import Popen, PIPE\nfrom gerapy import get_logger\nfrom gerapy.server.core.response import JsonResponse\nfrom gerapy.cmd.init import PROJECTS_FOLDER\nfrom gerapy.server.server.settings import TIME_ZONE\nfrom gerapy.server.core.models import Client, Project, Deploy, Monitor, Task\nfrom gerapy.server.core.build import build_project, find_egg\nfrom gerapy.server.core.utils import IGNORES, scrapyd_url, log_url, get_tree, get_scrapyd, process_html, bytes2str, \\\n clients_of_task, get_job_id\nfrom django_apscheduler.models import DjangoJob, DjangoJobExecution\nfrom django.core.files.storage import FileSystemStorage\nimport zipfile",
"logger = get_logger(__name__)",
"\n@api_view(['GET'])\n# @permission_classes([IsAuthenticated])\ndef index(request):\n \"\"\"\n render index page\n :param request: request object\n :return: page\n \"\"\"\n return render(request, 'index.html')",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef index_status(request):\n \"\"\"\n index statistics\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'GET':\n clients = Client.objects.all()\n data = {\n 'success': 0,\n 'error': 0,\n 'project': 0,\n }\n # clients info\n for client in clients:\n try:\n requests.get(scrapyd_url(client.ip, client.port), timeout=1)\n data['success'] += 1\n except ConnectionError:\n data['error'] += 1\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n files = os.listdir(path)\n # projects info\n for file in files:\n if os.path.isdir(join(path, file)) and not file in IGNORES:\n data['project'] += 1\n return JsonResponse(data)",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef client_index(request):\n \"\"\"\n get client list\n :param request: request object\n :return: client list\n \"\"\"\n return HttpResponse(serialize('json', Client.objects.order_by('-id')))",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef client_info(request, client_id):\n \"\"\"\n get client info\n :param request: request object\n :param id: client id\n :return: json\n \"\"\"\n if request.method == 'GET':\n return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef client_status(request, client_id):\n \"\"\"\n get client status\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'GET':\n # get client object\n client = Client.objects.get(id=client_id)\n requests.get(scrapyd_url(client.ip, client.port), timeout=3)\n return JsonResponse({'result': '1'})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef client_update(request, client_id):\n \"\"\"\n update client info\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'POST':\n client = Client.objects.filter(id=client_id)\n data = json.loads(request.body)\n client.update(**data)\n return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef client_create(request):\n \"\"\"\n create a client\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n client = Client.objects.create(**data)\n return JsonResponse(model_to_dict(client))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef client_remove(request, client_id):\n \"\"\"\n remove a client\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'POST':\n client = Client.objects.get(id=client_id)\n # delete deploy\n Deploy.objects.filter(client=client).delete()\n # delete client\n Client.objects.filter(id=client_id).delete()\n return JsonResponse({'result': '1'})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef spider_list(request, client_id, project_name):\n \"\"\"\n get spider list from one client\n :param request: request Object\n :param client_id: client id\n :param project_name: project name\n :return: json\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)\n spiders = scrapyd.list_spiders(project_name)\n spiders = [{'name': spider, 'id': index + 1} for index, spider in enumerate(spiders)]\n return JsonResponse(spiders)",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef spider_start(request, client_id, project_name, spider_name):\n \"\"\"\n start a spider\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param spider_name: spider name\n :return: json\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)\n job = scrapyd.schedule(project_name, spider_name)\n return JsonResponse({'job': job})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_list(request, client_id):\n \"\"\"\n project deployed list on one client\n :param request: request object\n :param client_id: client id\n :return: json\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)\n projects = scrapyd.list_projects()\n return JsonResponse(projects)",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_index(request):\n \"\"\"\n project index list\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'GET':\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n files = os.listdir(path)\n project_list = []\n for file in files:\n if os.path.isdir(join(path, file)) and not file in IGNORES:\n project_list.append({'name': file})\n return JsonResponse(project_list)",
"\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef project_configure(request, project_name):\n \"\"\"\n get configuration\n :param request: request object\n :param project_name: project name\n :return: json\n \"\"\"\n # get configuration\n if request.method == 'GET':\n project = Project.objects.get(name=project_name)\n project = model_to_dict(project)\n project['configuration'] = json.loads(project['configuration']) if project['configuration'] else None\n return JsonResponse(project)\n \n # update configuration\n elif request.method == 'POST':\n project = Project.objects.filter(name=project_name)\n data = json.loads(request.body)\n configuration = json.dumps(data.get('configuration'), ensure_ascii=False)\n project.update(**{'configuration': configuration})\n ",
" # for safe protection\n project_name = re.sub('[\\!\\@\\#\\$\\;\\&\\*\\~\\\"\\'\\{\\}\\]\\[\\-\\+\\%\\^]+', '', project_name)",
" # execute generate cmd\n cmd = ' '.join(['gerapy', 'generate', project_name])\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n \n if not stderr:\n return JsonResponse({'status': '1'})\n else:\n return JsonResponse({'status': '0', 'message': stderr})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_tree(request, project_name):\n \"\"\"\n get file tree of project\n :param request: request object\n :param project_name: project name\n :return: json of tree\n \"\"\"\n if request.method == 'GET':\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n # get tree data\n tree = get_tree(join(path, project_name))\n return JsonResponse(tree)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_create(request):\n \"\"\"\n create a configurable project\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n data['configurable'] = 1\n project, result = Project.objects.update_or_create(**data)\n # generate a single project folder\n path = join(os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER)), data['name'])\n os.mkdir(path)\n return JsonResponse(model_to_dict(project))",
"\n@api_view(['POST'])\n# @permission_classes([IsAuthenticated])\ndef project_upload(request):\n \"\"\"\n upload project\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n file = request.FILES['file']\n file_name = file.name\n fs = FileSystemStorage(PROJECTS_FOLDER)\n zip_file_name = fs.save(file_name, file)\n logger.debug('zip file name %s', zip_file_name)\n # extract zip file\n with zipfile.ZipFile(join(PROJECTS_FOLDER, zip_file_name), 'r') as zip_ref:\n zip_ref.extractall(PROJECTS_FOLDER)\n logger.debug('extracted files to %s', PROJECTS_FOLDER)\n return JsonResponse({'status': True})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_clone(request):\n \"\"\"\n clone project from github\n :param request: request object\n :return: json\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n address = data.get('address')\n if not address.startswith('http'):\n return JsonResponse({'status': False})\n address = address + '.git' if not address.endswith('.git') else address\n cmd = 'git clone {address} {target}'.format(address=address, target=join(PROJECTS_FOLDER, Path(address).stem))\n logger.debug('clone cmd %s', cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n logger.debug('clone run result %s', stdout)\n if stderr: logger.error(stderr)\n return JsonResponse({'status': True}) if not stderr else JsonResponse({'status': False})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_remove(request, project_name):\n \"\"\"\n remove project from disk and db\n :param request: request object\n :param project_name: project name\n :return: result of remove\n \"\"\"\n if request.method == 'POST':\n # delete deployments\n project = Project.objects.get(name=project_name)\n Deploy.objects.filter(project=project).delete()\n # delete project\n result = Project.objects.filter(name=project_name).delete()\n # get project path\n path = join(os.path.abspath(os.getcwd()), PROJECTS_FOLDER)\n project_path = join(path, project_name)\n # delete project file tree\n if exists(project_path):\n rmtree(project_path)\n return JsonResponse({'result': result})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef project_version(request, client_id, project_name):\n \"\"\"\n get project deploy version\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :return: deploy version of project\n \"\"\"\n if request.method == 'GET':\n # get client and project model\n client = Client.objects.get(id=client_id)\n project = Project.objects.get(name=project_name)\n scrapyd = get_scrapyd(client)\n # if deploy info exists in db, return it\n if Deploy.objects.filter(client=client, project=project):\n deploy = Deploy.objects.get(client=client, project=project)\n # if deploy info does not exists in db, create deploy info\n else:\n try:\n versions = scrapyd.list_versions(project_name)\n except ConnectionError:\n return JsonResponse({'message': 'Connect Error'}, status=500)\n if len(versions) > 0:\n version = versions[-1]\n deployed_at = timezone.datetime.fromtimestamp(int(version), tz=pytz.timezone(TIME_ZONE))\n else:\n deployed_at = None\n deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at)\n # return deploy json info\n return JsonResponse(model_to_dict(deploy))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_deploy(request, client_id, project_name):\n \"\"\"\n deploy project operation\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :return: json of deploy result\n \"\"\"\n if request.method == 'POST':\n # get project folder\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n project_path = join(path, project_name)\n # find egg file\n egg = find_egg(project_path)\n if not egg:\n return JsonResponse({'message': 'egg not found'}, status=500)\n egg_file = open(join(project_path, egg), 'rb')\n # get client and project model\n client = Client.objects.get(id=client_id)\n project = Project.objects.get(name=project_name)\n # execute deploy operation\n scrapyd = get_scrapyd(client)\n scrapyd.add_version(project_name, int(time.time()), egg_file.read())\n # update deploy info\n deployed_at = timezone.now()\n Deploy.objects.filter(client=client, project=project).delete()\n deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at,\n description=project.description)\n return JsonResponse(model_to_dict(deploy))",
"\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef project_build(request, project_name):\n \"\"\"\n get build info or execute build operation\n :param request: request object\n :param project_name: project name\n :return: json\n \"\"\"\n # get project folder\n path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))\n project_path = join(path, project_name)\n \n # get build version\n if request.method == 'GET':\n egg = find_egg(project_path)\n # if built, save or update project to db\n if egg:\n built_at = timezone.datetime.fromtimestamp(os.path.getmtime(join(project_path, egg)),\n tz=pytz.timezone(TIME_ZONE))\n if not Project.objects.filter(name=project_name):\n Project(name=project_name, built_at=built_at, egg=egg).save()\n model = Project.objects.get(name=project_name)\n else:\n model = Project.objects.get(name=project_name)\n model.built_at = built_at\n model.egg = egg\n model.save()\n # if not built, just save project name to db\n else:\n if not Project.objects.filter(name=project_name):\n Project(name=project_name).save()\n model = Project.objects.get(name=project_name)\n # transfer model to dict then dumps it to json\n data = model_to_dict(model)\n return JsonResponse(data)\n \n # build operation manually by clicking button\n elif request.method == 'POST':\n data = json.loads(request.body)\n description = data['description']\n build_project(project_name)\n egg = find_egg(project_path)\n if not egg:\n return JsonResponse({'message': 'egg not found'}, status=500)\n # update built_at info\n built_at = timezone.now()\n # if project does not exists in db, create it\n if not Project.objects.filter(name=project_name):\n Project(name=project_name, description=description, built_at=built_at, egg=egg).save()\n model = Project.objects.get(name=project_name)\n # if project exists, update egg, description, built_at info\n else:\n model = Project.objects.get(name=project_name)\n model.built_at = built_at\n model.egg = egg\n model.description = description\n model.save()\n # transfer model to dict then dumps it to json\n data = model_to_dict(model)\n return JsonResponse(data)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_parse(request, project_name):\n \"\"\"\n parse project\n :param request: request object\n :param project_name: project name\n :return: requests, items, response\n \"\"\"\n if request.method == 'POST':\n project_path = join(PROJECTS_FOLDER, project_name)\n data = json.loads(request.body)\n logger.debug('post data %s', data)\n spider_name = data.get('spider')\n args = {\n 'start': data.get('start', False),\n 'method': data.get('method', 'GET'),\n 'url': data.get('url'),\n 'callback': data.get('callback'),\n 'cookies': \"'\" + json.dumps(data.get('cookies', {}), ensure_ascii=False) + \"'\",\n 'headers': \"'\" + json.dumps(data.get('headers', {}), ensure_ascii=False) + \"'\",\n 'meta': \"'\" + json.dumps(data.get('meta', {}), ensure_ascii=False) + \"'\",\n 'dont_filter': data.get('dont_filter', False),\n 'priority': data.get('priority', 0),\n }\n # set request body\n body = data.get('body', '')\n if args.get('method').lower() != 'get':\n args['body'] = \"'\" + json.dumps(body, ensure_ascii=False) + \"'\"\n \n args_cmd = ' '.join(\n ['--{arg} {value}'.format(arg=arg, value=value) for arg, value in args.items()])\n logger.debug('args cmd %s', args_cmd)\n cmd = 'gerapy parse {args_cmd} {project_path} {spider_name}'.format(\n args_cmd=args_cmd,\n project_path=project_path,\n spider_name=spider_name\n )\n logger.debug('parse cmd %s', cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)\n stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())\n logger.debug('stdout %s, stderr %s', stdout, stderr)\n if not stderr:\n return JsonResponse({'status': True, 'result': json.loads(stdout)})\n else:\n return JsonResponse({'status': False, 'message': stderr})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_read(request):\n \"\"\"\n get content of project file\n :param request: request object\n :return: file content\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['label'])\n # binary file\n with open(path, 'rb') as f:\n return HttpResponse(f.read().decode('utf-8'))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_update(request):\n \"\"\"\n update project file\n :param request: request object\n :return: result of update\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['label'])\n code = data['code']\n with open(path, 'w', encoding='utf-8') as f:\n f.write(code)\n return JsonResponse({'result': '1'})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_create(request):\n \"\"\"\n create project file\n :param request: request object\n :return: result of create\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['name'])\n open(path, 'w', encoding='utf-8').close()\n return JsonResponse({'result': '1'})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_delete(request):\n \"\"\"\n delete project file\n :param request: request object\n :return: result of delete\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n path = join(data['path'], data['label'])\n result = os.remove(path)\n return JsonResponse({'result': result})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef project_file_rename(request):\n \"\"\"\n rename file name\n :param request: request object\n :return: result of rename\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n pre = join(data['path'], data['pre'])\n new = join(data['path'], data['new'])\n os.rename(pre, new)\n return JsonResponse({'result': '1'})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef job_list(request, client_id, project_name):\n \"\"\"\n get job list of project from one client\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :return: list of jobs\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n scrapyd = get_scrapyd(client)",
" result = scrapyd.list_jobs(project_name)\n jobs = []\n statuses = ['pending', 'running', 'finished']\n for status in statuses:\n for job in result.get(status):\n job['status'] = status\n jobs.append(job)\n return JsonResponse(jobs)\n ",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef job_log(request, client_id, project_name, spider_name, job_id):\n \"\"\"\n get log of jog\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param spider_name: spider name\n :param job_id: job id\n :return: log of job\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n # get log url\n url = log_url(client.ip, client.port, project_name, spider_name, job_id)",
" # get last 1000 bytes of log\n response = requests.get(url, timeout=5, headers={\n 'Range': 'bytes=-1000'\n }, auth=(client.username, client.password) if client.auth else None)\n # Get encoding\n encoding = response.apparent_encoding\n # log not found\n if response.status_code == 404:\n return JsonResponse({'message': 'Log Not Found'}, status=404)\n # bytes to string\n text = response.content.decode(encoding, errors='replace')\n return HttpResponse(text)",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef job_cancel(request, client_id, project_name, job_id):\n \"\"\"\n cancel a job\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param job_id: job id\n :return: json of cancel\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)",
" scrapyd = get_scrapyd(client)\n result = scrapyd.cancel(project_name, job_id)\n return JsonResponse(result)",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef del_version(request, client_id, project, version):\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)",
" scrapyd = get_scrapyd(client)\n result = scrapyd.delete_version(project=project, version=version)\n return JsonResponse(result)",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef del_project(request, client_id, project):\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)",
" scrapyd = get_scrapyd(client)\n result = scrapyd.delete_project(project=project)\n return JsonResponse(result)",
"",
"@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef monitor_db_list(request):\n \"\"\"\n get monitor db list\n :param request: request object\n :return: json of db list\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n url = data['url']\n type = data['type']\n if type == 'MongoDB':\n client = pymongo.MongoClient(url)\n dbs = client.list_database_names()\n return JsonResponse(dbs)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef monitor_collection_list(request):\n \"\"\"\n get monitor collection list\n :param request: request object\n :return: json of collection list\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n url = data['url']\n db = data['db']\n type = data['type']\n if type == 'MongoDB':\n client = pymongo.MongoClient(url)\n db = client[db]\n collections = db.collection_names()\n return JsonResponse(collections)",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef monitor_create(request):\n \"\"\"\n create a monitor\n :param request: request object\n :return: json of create\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n data = data['form']\n data['configuration'] = json.dumps(data['configuration'], ensure_ascii=False)\n monitor = Monitor.objects.create(**data)\n return JsonResponse(model_to_dict(monitor))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef task_create(request):\n \"\"\"\n add task\n :param request: request object\n :return: Bool\n \"\"\"\n if request.method == 'POST':\n data = json.loads(request.body)\n task = Task.objects.create(clients=json.dumps(data.get('clients'), ensure_ascii=False),\n project=data.get('project'),\n name=data.get('name'),\n spider=data.get('spider'),\n trigger=data.get('trigger'),\n configuration=json.dumps(data.get('configuration'), ensure_ascii=False),\n modified=1)\n return JsonResponse({'result': '1', 'data': model_to_dict(task)})",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef task_update(request, task_id):\n \"\"\"\n update task info\n :param request: request object\n :param task_id: task id\n :return: json\n \"\"\"\n if request.method == 'POST':\n task = Task.objects.filter(id=task_id)\n data = json.loads(request.body)\n data['clients'] = json.dumps(data.get('clients'), ensure_ascii=False)\n data['configuration'] = json.dumps(data.get('configuration'), ensure_ascii=False)\n data['modified'] = 1\n task.update(**data)\n return JsonResponse(model_to_dict(Task.objects.get(id=task_id)))",
"\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef task_remove(request, task_id):\n \"\"\"\n remove task by task_id\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':",
" # delete job from DjangoJob\n task = Task.objects.get(id=task_id)\n clients = clients_of_task(task)\n for client in clients:\n job_id = get_job_id(client, task)\n DjangoJob.objects.filter(name=job_id).delete()\n # delete task\n Task.objects.filter(id=task_id).delete()\n return JsonResponse({'result': '1'})\n ",
"",
"@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef task_info(request, task_id):\n \"\"\"\n get task info\n :param request: request object\n :param task_id: task id\n :return: json\n \"\"\"\n if request.method == 'GET':\n task = Task.objects.get(id=task_id)\n data = model_to_dict(task)\n data['clients'] = json.loads(data.get('clients'))\n data['configuration'] = json.loads(data.get('configuration'))\n return JsonResponse({'data': data})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef task_index(request):\n \"\"\"\n get all tasks\n :param request:\n :return:\n \"\"\"\n if request.method == 'GET':\n tasks = Task.objects.values()\n return JsonResponse({'result': '1', 'data': tasks})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef task_status(request, task_id):\n \"\"\"\n get task status info\n :param request: request object\n :param task_id: task id\n :return:\n \"\"\"\n if request.method == 'GET':\n result = []\n task = Task.objects.get(id=task_id)\n clients = clients_of_task(task)\n for client in clients:\n job_id = get_job_id(client, task)\n jobs = DjangoJob.objects.filter(name=job_id)\n logger.debug('jobs from djangojob %s', jobs)\n # if job does not exist, for date mode exceed time\n if not jobs: continue\n job = DjangoJob.objects.get(name=job_id)\n executions = serialize('json', DjangoJobExecution.objects.filter(job=job))\n result.append({\n 'client': model_to_dict(client),\n 'next': job.next_run_time,\n 'executions': json.loads(executions)\n })\n return JsonResponse({'data': result})",
"\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef render_html(request):\n \"\"\"\n render html with url\n :param request:\n :return:\n \"\"\"\n if request.method == 'GET':\n url = request.GET.get('url')\n url = unquote(base64.b64decode(url).decode('utf-8'))\n js = request.GET.get('js', 0)\n script = request.GET.get('script')",
" response = requests.get(url, timeout=5)\n response.encoding = response.apparent_encoding\n html = process_html(response.text)\n return HttpResponse(html)"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"apscheduler==3.5.1\ncryptography==2.8\ndjango==1.11.29\ndjango-cors-headers==3.2.0\ndjango-apscheduler==0.3.0\nfurl==2.1.0\njinja2==2.10.1",
"scrapy>=1.4.0",
"scrapy-redis==0.6.8\nscrapy-splash==0.7.2\npython-scrapyd-api==2.1.2\nredis==2.10.5",
"requests>=2.20.0",
"pymongo==3.9.0\npymysql==0.7.10\npyquery==1.2.17\nbeautifulsoup4==4.7.0\ndjangorestframework==3.9.2\nwebsocket==0.2.1\npyppeteer==0.0.25"
] |
[
1,
0,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"apscheduler==3.5.1\ncryptography==2.8\ndjango==1.11.29\ndjango-cors-headers==3.2.0\ndjango-apscheduler==0.3.0\nfurl==2.1.0\njinja2==2.10.1",
"scrapy==1.5.0",
"scrapy-redis==0.6.8\nscrapy-splash==0.7.2\npython-scrapyd-api==2.1.2\nredis==2.10.5",
"requests==2.20.0",
"pymongo==3.9.0\npymysql==0.7.10\npyquery==1.2.17\nbeautifulsoup4==4.7.0\ndjangorestframework==3.9.2\nwebsocket==0.2.1\npyppeteer==0.0.25"
] |
[
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [13, 2, 925, 14], "buggy_code_start_loc": [10, 1, 0, 8], "filenames": ["README.md", "gerapy/__version__.py", "gerapy/server/core/views.py", "requirements.txt"], "fixing_code_end_loc": [9, 2, 909, 14], "fixing_code_start_loc": [9, 1, 1, 8], "message": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:gerapy:gerapy:*:*:*:*:*:*:*:*", "matchCriteriaId": "F5605B92-63EA-43FE-984C-A3B11BACD185", "versionEndExcluding": "0.9.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "0.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package Gerapy from 0 and before 0.9.3. The input being passed to Popen, via the project_configure endpoint, isn\u2019t being sanitized."}, {"lang": "es", "value": "Esto afecta al paquete Gerapy desde 0 y versiones anteriores a 0.9.3. La entrada que esta siendo pasada a Popen, por medio del endpoint project_configure no es saneada"}], "evaluatorComment": null, "id": "CVE-2020-7698", "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"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2020-07-29T13:15:10.397", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-GERAPY-572470"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-78"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2"}, "type": "CWE-78"}
| 316
|
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 * spell.c: code for spell checking\n *\n * See spellfile.c for the Vim spell file format.\n *\n * The spell checking mechanism uses a tree (aka trie). Each node in the tree\n * has a list of bytes that can appear (siblings). For each byte there is a\n * pointer to the node with the byte that follows in the word (child).\n *\n * A NUL byte is used where the word may end. The bytes are sorted, so that\n * binary searching can be used and the NUL bytes are at the start. The\n * number of possible bytes is stored before the list of bytes.\n *\n * The tree uses two arrays: \"byts\" stores the characters, \"idxs\" stores\n * either the next index or flags. The tree starts at index 0. For example,\n * to lookup \"vi\" this sequence is followed:\n *\ti = 0\n *\tlen = byts[i]\n *\tn = where \"v\" appears in byts[i + 1] to byts[i + len]\n *\ti = idxs[n]\n *\tlen = byts[i]\n *\tn = where \"i\" appears in byts[i + 1] to byts[i + len]\n *\ti = idxs[n]\n *\tlen = byts[i]\n *\tfind that byts[i + 1] is 0, idxs[i + 1] has flags for \"vi\".\n *\n * There are two word trees: one with case-folded words and one with words in\n * original case. The second one is only used for keep-case words and is\n * usually small.\n *\n * There is one additional tree for when not all prefixes are applied when\n * generating the .spl file. This tree stores all the possible prefixes, as\n * if they were words. At each word (prefix) end the prefix nr is stored, the\n * following word must support this prefix nr. And the condition nr is\n * stored, used to lookup the condition that the word must match with.\n *\n * Thanks to Olaf Seibert for providing an example implementation of this tree\n * and the compression mechanism.\n * LZ trie ideas:\n *\thttp://www.irb.hr/hr/home/ristov/papers/RistovLZtrieRevision1.pdf\n * More papers: http://www-igm.univ-mlv.fr/~laporte/publi_en.html\n *\n * Matching involves checking the caps type: Onecap ALLCAP KeepCap.\n *\n * Why doesn't Vim use aspell/ispell/myspell/etc.?\n * See \":help develop-spell\".\n */",
"#define IN_SPELL_C\n#include \"vim.h\"",
"#if defined(FEAT_SPELL) || defined(PROTO)",
"#ifndef UNIX\t\t// it's in os_unix.h for Unix\n# include <time.h>\t// for time_t\n#endif",
"#define REGION_ALL 0xff\t\t// word valid in all regions",
"// Result values. Lower number is accepted over higher one.\n#define SP_BANNED\t(-1)\n#define SP_OK\t\t0\n#define SP_RARE\t\t1\n#define SP_LOCAL\t2\n#define SP_BAD\t\t3",
"/*\n * Structure to store info for word matching.\n */\ntypedef struct matchinf_S\n{\n langp_T\t*mi_lp;\t\t\t// info for language and region",
" // pointers to original text to be checked\n char_u\t*mi_word;\t\t// start of word being checked\n char_u\t*mi_end;\t\t// end of matching word so far\n char_u\t*mi_fend;\t\t// next char to be added to mi_fword\n char_u\t*mi_cend;\t\t// char after what was used for\n\t\t\t\t\t// mi_capflags",
" // case-folded text\n char_u\tmi_fword[MAXWLEN + 1];\t// mi_word case-folded\n int\t\tmi_fwordlen;\t\t// nr of valid bytes in mi_fword",
" // for when checking word after a prefix\n int\t\tmi_prefarridx;\t\t// index in sl_pidxs with list of\n\t\t\t\t\t// affixID/condition\n int\t\tmi_prefcnt;\t\t// number of entries at mi_prefarridx\n int\t\tmi_prefixlen;\t\t// byte length of prefix\n int\t\tmi_cprefixlen;\t\t// byte length of prefix in original\n\t\t\t\t\t// case",
" // for when checking a compound word\n int\t\tmi_compoff;\t\t// start of following word offset\n char_u\tmi_compflags[MAXWLEN];\t// flags for compound words used\n int\t\tmi_complen;\t\t// nr of compound words used\n int\t\tmi_compextra;\t\t// nr of COMPOUNDROOT words",
" // others\n int\t\tmi_result;\t\t// result so far: SP_BAD, SP_OK, etc.\n int\t\tmi_capflags;\t\t// WF_ONECAP WF_ALLCAP WF_KEEPCAP\n win_T\t*mi_win;\t\t// buffer being checked",
" // for NOBREAK\n int\t\tmi_result2;\t\t// \"mi_resul\" without following word\n char_u\t*mi_end2;\t\t// \"mi_end\" without following word\n} matchinf_T;",
"\nstatic int spell_mb_isword_class(int cl, win_T *wp);",
"// mode values for find_word\n#define FIND_FOLDWORD\t 0\t// find word case-folded\n#define FIND_KEEPWORD\t 1\t// find keep-case word\n#define FIND_PREFIX\t 2\t// find word after prefix\n#define FIND_COMPOUND\t 3\t// find case-folded compound word\n#define FIND_KEEPCOMPOUND 4\t// find keep-case compound word",
"static void find_word(matchinf_T *mip, int mode);\nstatic void find_prefix(matchinf_T *mip, int mode);\nstatic int fold_more(matchinf_T *mip);\nstatic void spell_load_cb(char_u *fname, void *cookie);\nstatic int count_syllables(slang_T *slang, char_u *word);\nstatic void clear_midword(win_T *buf);\nstatic void use_midword(slang_T *lp, win_T *buf);\nstatic int find_region(char_u *rp, char_u *region);\nstatic void spell_soundfold_sofo(slang_T *slang, char_u *inword, char_u *res);\nstatic void spell_soundfold_sal(slang_T *slang, char_u *inword, char_u *res);\nstatic void spell_soundfold_wsal(slang_T *slang, char_u *inword, char_u *res);\nstatic void dump_word(slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T lnum);\nstatic linenr_T dump_prefixes(slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T startlnum);",
"/*\n * Main spell-checking function.\n * \"ptr\" points to a character that could be the start of a word.\n * \"*attrp\" is set to the highlight index for a badly spelled word. For a\n * non-word or when it's OK it remains unchanged.\n * This must only be called when 'spelllang' is not empty.\n *\n * \"capcol\" is used to check for a Capitalised word after the end of a\n * sentence. If it's zero then perform the check. Return the column where to\n * check next, or -1 when no sentence end was found. If it's NULL then don't\n * worry.\n *\n * Returns the length of the word in bytes, also when it's OK, so that the\n * caller can skip over the word.\n */\n int\nspell_check(\n win_T\t*wp,\t\t// current window\n char_u\t*ptr,\n hlf_T\t*attrp,\n int\t\t*capcol,\t// column to check for Capital\n int\t\tdocount)\t// count good words\n{\n matchinf_T\tmi;\t\t// Most things are put in \"mi\" so that it can\n\t\t\t\t// be passed to functions quickly.\n int\t\tnrlen = 0;\t// found a number first\n int\t\tc;\n int\t\twrongcaplen = 0;\n int\t\tlpi;\n int\t\tcount_word = docount;\n int\t\tuse_camel_case = *wp->w_s->b_p_spo != NUL;\n int\t\tcamel_case = 0;",
" // A word never starts at a space or a control character. Return quickly\n // then, skipping over the character.\n if (*ptr <= ' ')\n\treturn 1;",
" // Return here when loading language files failed.\n if (wp->w_s->b_langp.ga_len == 0)\n\treturn 1;",
" CLEAR_FIELD(mi);",
" // A number is always OK. Also skip hexadecimal numbers 0xFF99 and\n // 0X99FF. But always do check spelling to find \"3GPP\" and \"11\n // julifeest\".\n if (*ptr >= '0' && *ptr <= '9')\n {\n\tif (*ptr == '0' && (ptr[1] == 'b' || ptr[1] == 'B'))\n\t mi.mi_end = skipbin(ptr + 2);\n\telse if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X'))\n\t mi.mi_end = skiphex(ptr + 2);\n\telse\n\t mi.mi_end = skipdigits(ptr);\n\tnrlen = (int)(mi.mi_end - ptr);\n }",
" // Find the normal end of the word (until the next non-word character).\n mi.mi_word = ptr;\n mi.mi_fend = ptr;\n if (spell_iswordp(mi.mi_fend, wp))\n {\n\tint prev_upper;\n\tint this_upper = FALSE; // init for gcc",
"\tif (use_camel_case)\n\t{\n\t c = PTR2CHAR(mi.mi_fend);\n\t this_upper = SPELL_ISUPPER(c);\n\t}",
"\tdo\n\t{\n\t MB_PTR_ADV(mi.mi_fend);\n\t if (use_camel_case)\n\t {\n\t\tprev_upper = this_upper;\n\t\tc = PTR2CHAR(mi.mi_fend);\n\t\tthis_upper = SPELL_ISUPPER(c);\n\t\tcamel_case = !prev_upper && this_upper;\n\t }\n\t} while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp)\n\t\t\t\t\t\t\t && !camel_case);",
"\tif (capcol != NULL && *capcol == 0 && wp->w_s->b_cap_prog != NULL)\n\t{\n\t // Check word starting with capital letter.\n\t c = PTR2CHAR(ptr);\n\t if (!SPELL_ISUPPER(c))\n\t\twrongcaplen = (int)(mi.mi_fend - ptr);\n\t}\n }\n if (capcol != NULL)\n\t*capcol = -1;",
" // We always use the characters up to the next non-word character,\n // also for bad words.\n mi.mi_end = mi.mi_fend;",
" // Check caps type later.\n mi.mi_capflags = 0;\n mi.mi_cend = NULL;\n mi.mi_win = wp;",
" // case-fold the word with one non-word character, so that we can check\n // for the word end.\n if (*mi.mi_fend != NUL)\n\tMB_PTR_ADV(mi.mi_fend);",
" (void)spell_casefold(wp, ptr, (int)(mi.mi_fend - ptr), mi.mi_fword,\n\t\t\t\t\t\t\t MAXWLEN + 1);\n mi.mi_fwordlen = (int)STRLEN(mi.mi_fword);",
" if (camel_case && mi.mi_fwordlen > 0)\n\t// Introduce a fake word end space into the folded word.\n\tmi.mi_fword[mi.mi_fwordlen - 1] = ' ';",
" // The word is bad unless we recognize it.\n mi.mi_result = SP_BAD;\n mi.mi_result2 = SP_BAD;",
" /*\n * Loop over the languages specified in 'spelllang'.\n * We check them all, because a word may be matched longer in another\n * language.\n */\n for (lpi = 0; lpi < wp->w_s->b_langp.ga_len; ++lpi)\n {\n\tmi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, lpi);",
"\t// If reloading fails the language is still in the list but everything\n\t// has been cleared.\n\tif (mi.mi_lp->lp_slang->sl_fidxs == NULL)\n\t continue;",
"\t// Check for a matching word in case-folded words.\n\tfind_word(&mi, FIND_FOLDWORD);",
"\t// Check for a matching word in keep-case words.\n\tfind_word(&mi, FIND_KEEPWORD);",
"\t// Check for matching prefixes.\n\tfind_prefix(&mi, FIND_FOLDWORD);",
"\t// For a NOBREAK language, may want to use a word without a following\n\t// word as a backup.\n\tif (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD\n\t\t\t\t\t\t && mi.mi_result2 != SP_BAD)\n\t{\n\t mi.mi_result = mi.mi_result2;\n\t mi.mi_end = mi.mi_end2;\n\t}",
"\t// Count the word in the first language where it's found to be OK.\n\tif (count_word && mi.mi_result == SP_OK)\n\t{\n\t count_common_word(mi.mi_lp->lp_slang, ptr,\n\t\t\t\t\t\t (int)(mi.mi_end - ptr), 1);\n\t count_word = FALSE;\n\t}\n }",
" if (mi.mi_result != SP_OK)\n {\n\t// If we found a number skip over it. Allows for \"42nd\". Do flag\n\t// rare and local words, e.g., \"3GPP\".\n\tif (nrlen > 0)\n\t{\n\t if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)\n\t\treturn nrlen;\n\t}",
"\t// When we are at a non-word character there is no error, just\n\t// skip over the character (try looking for a word after it).\n\telse if (!spell_iswordp_nmw(ptr, wp))\n\t{\n\t if (capcol != NULL && wp->w_s->b_cap_prog != NULL)\n\t {\n\t\tregmatch_T\tregmatch;\n\t\tint\t\tr;",
"\t\t// Check for end of sentence.\n\t\tregmatch.regprog = wp->w_s->b_cap_prog;\n\t\tregmatch.rm_ic = FALSE;\n\t\tr = vim_regexec(®match, ptr, 0);\n\t\twp->w_s->b_cap_prog = regmatch.regprog;\n\t\tif (r)\n\t\t *capcol = (int)(regmatch.endp[0] - ptr);\n\t }",
"\t if (has_mbyte)\n\t\treturn (*mb_ptr2len)(ptr);\n\t return 1;\n\t}\n\telse if (mi.mi_end == ptr)\n\t // Always include at least one character. Required for when there\n\t // is a mixup in \"midword\".\n\t MB_PTR_ADV(mi.mi_end);\n\telse if (mi.mi_result == SP_BAD\n\t\t&& LANGP_ENTRY(wp->w_s->b_langp, 0)->lp_slang->sl_nobreak)\n\t{\n\t char_u\t*p, *fp;\n\t int\t\tsave_result = mi.mi_result;",
"\t // First language in 'spelllang' is NOBREAK. Find first position\n\t // at which any word would be valid.\n\t mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, 0);\n\t if (mi.mi_lp->lp_slang->sl_fidxs != NULL)\n\t {\n\t\tp = mi.mi_word;\n\t\tfp = mi.mi_fword;\n\t\tfor (;;)\n\t\t{\n\t\t MB_PTR_ADV(p);\n\t\t MB_PTR_ADV(fp);\n\t\t if (p >= mi.mi_end)\n\t\t\tbreak;\n\t\t mi.mi_compoff = (int)(fp - mi.mi_fword);\n\t\t find_word(&mi, FIND_COMPOUND);\n\t\t if (mi.mi_result != SP_BAD)\n\t\t {\n\t\t\tmi.mi_end = p;\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t\tmi.mi_result = save_result;\n\t }\n\t}",
"\tif (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)\n\t *attrp = HLF_SPB;\n\telse if (mi.mi_result == SP_RARE)\n\t *attrp = HLF_SPR;\n\telse\n\t *attrp = HLF_SPL;\n }",
" if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE))\n {\n\t// Report SpellCap only when the word isn't badly spelled.\n\t*attrp = HLF_SPC;\n\treturn wrongcaplen;\n }",
" return (int)(mi.mi_end - ptr);\n}",
"/*\n * Check if the word at \"mip->mi_word\" is in the tree.\n * When \"mode\" is FIND_FOLDWORD check in fold-case word tree.\n * When \"mode\" is FIND_KEEPWORD check in keep-case word tree.\n * When \"mode\" is FIND_PREFIX check for word after prefix in fold-case word\n * tree.\n *\n * For a match mip->mi_result is updated.\n */\n static void\nfind_word(matchinf_T *mip, int mode)\n{\n idx_T\tarridx = 0;\n int\t\tendlen[MAXWLEN]; // length at possible word endings\n idx_T\tendidx[MAXWLEN]; // possible word endings\n int\t\tendidxcnt = 0;\n int\t\tlen;\n int\t\twlen = 0;\n int\t\tflen;\n int\t\tc;\n char_u\t*ptr;\n idx_T\tlo, hi, m;\n char_u\t*s;\n char_u\t*p;\n int\t\tres = SP_BAD;\n slang_T\t*slang = mip->mi_lp->lp_slang;\n unsigned\tflags;\n char_u\t*byts;\n idx_T\t*idxs;\n int\t\tword_ends;\n int\t\tprefix_found;\n int\t\tnobreak_result;",
" if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND)\n {\n\t// Check for word with matching case in keep-case tree.\n\tptr = mip->mi_word;\n\tflen = 9999;\t\t // no case folding, always enough bytes\n\tbyts = slang->sl_kbyts;\n\tidxs = slang->sl_kidxs;",
"\tif (mode == FIND_KEEPCOMPOUND)\n\t // Skip over the previously found word(s).\n\t wlen += mip->mi_compoff;\n }\n else\n {\n\t// Check for case-folded in case-folded tree.\n\tptr = mip->mi_fword;\n\tflen = mip->mi_fwordlen; // available case-folded bytes\n\tbyts = slang->sl_fbyts;\n\tidxs = slang->sl_fidxs;",
"\tif (mode == FIND_PREFIX)\n\t{\n\t // Skip over the prefix.\n\t wlen = mip->mi_prefixlen;\n\t flen -= mip->mi_prefixlen;\n\t}\n\telse if (mode == FIND_COMPOUND)\n\t{\n\t // Skip over the previously found word(s).\n\t wlen = mip->mi_compoff;\n\t flen -= mip->mi_compoff;\n\t}",
" }",
" if (byts == NULL)\n\treturn;\t\t\t// array is empty",
" /*\n * Repeat advancing in the tree until:\n * - there is a byte that doesn't match,\n * - we reach the end of the tree,\n * - or we reach the end of the line.\n */\n for (;;)\n {\n\tif (flen <= 0 && *mip->mi_fend != NUL)\n\t flen = fold_more(mip);",
"\tlen = byts[arridx++];",
"\t// If the first possible byte is a zero the word could end here.\n\t// Remember this index, we first check for the longest word.\n\tif (byts[arridx] == 0)\n\t{\n\t if (endidxcnt == MAXWLEN)\n\t {\n\t\t// Must be a corrupted spell file.\n\t\temsg(_(e_format_error_in_spell_file));\n\t\treturn;\n\t }\n\t endlen[endidxcnt] = wlen;\n\t endidx[endidxcnt++] = arridx++;\n\t --len;",
"\t // Skip over the zeros, there can be several flag/region\n\t // combinations.\n\t while (len > 0 && byts[arridx] == 0)\n\t {\n\t\t++arridx;\n\t\t--len;\n\t }\n\t if (len == 0)\n\t\tbreak;\t // no children, word must end here\n\t}",
"\t// Stop looking at end of the line.\n\tif (ptr[wlen] == NUL)\n\t break;",
"\t// Perform a binary search in the list of accepted bytes.\n\tc = ptr[wlen];\n\tif (c == TAB)\t // <Tab> is handled like <Space>\n\t c = ' ';\n\tlo = arridx;\n\thi = arridx + len - 1;\n\twhile (lo < hi)\n\t{\n\t m = (lo + hi) / 2;\n\t if (byts[m] > c)\n\t\thi = m - 1;\n\t else if (byts[m] < c)\n\t\tlo = m + 1;\n\t else\n\t {\n\t\tlo = hi = m;\n\t\tbreak;\n\t }\n\t}",
"\t// Stop if there is no matching byte.\n\tif (hi < lo || byts[lo] != c)\n\t break;",
"\t// Continue at the child (if there is one).\n\tarridx = idxs[lo];\n\t++wlen;\n\t--flen;",
"\t// One space in the good word may stand for several spaces in the\n\t// checked word.\n\tif (c == ' ')\n\t{\n\t for (;;)\n\t {\n\t\tif (flen <= 0 && *mip->mi_fend != NUL)\n\t\t flen = fold_more(mip);\n\t\tif (ptr[wlen] != ' ' && ptr[wlen] != TAB)\n\t\t break;\n\t\t++wlen;\n\t\t--flen;\n\t }\n\t}\n }",
" /*\n * Verify that one of the possible endings is valid. Try the longest\n * first.\n */\n while (endidxcnt > 0)\n {\n\t--endidxcnt;\n\tarridx = endidx[endidxcnt];\n\twlen = endlen[endidxcnt];",
"\tif ((*mb_head_off)(ptr, ptr + wlen) > 0)\n\t continue;\t // not at first byte of character\n\tif (spell_iswordp(ptr + wlen, mip->mi_win))\n\t{\n\t if (slang->sl_compprog == NULL && !slang->sl_nobreak)\n\t\tcontinue;\t // next char is a word character\n\t word_ends = FALSE;\n\t}\n\telse\n\t word_ends = TRUE;\n\t// The prefix flag is before compound flags. Once a valid prefix flag\n\t// has been found we try compound flags.\n\tprefix_found = FALSE;",
"\tif (mode != FIND_KEEPWORD && has_mbyte)\n\t{\n\t // Compute byte length in original word, length may change\n\t // when folding case. This can be slow, take a shortcut when the\n\t // case-folded word is equal to the keep-case word.\n\t p = mip->mi_word;\n\t if (STRNCMP(ptr, p, wlen) != 0)\n\t {\n\t\tfor (s = ptr; s < ptr + wlen; MB_PTR_ADV(s))\n\t\t MB_PTR_ADV(p);\n\t\twlen = (int)(p - mip->mi_word);\n\t }\n\t}",
"\t// Check flags and region. For FIND_PREFIX check the condition and\n\t// prefix ID.\n\t// Repeat this if there are more flags/region alternatives until there\n\t// is a match.\n\tres = SP_BAD;\n\tfor (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0;\n\t\t\t\t\t\t\t --len, ++arridx)\n\t{\n\t flags = idxs[arridx];",
"\t // For the fold-case tree check that the case of the checked word\n\t // matches with what the word in the tree requires.\n\t // For keep-case tree the case is always right. For prefixes we\n\t // don't bother to check.\n\t if (mode == FIND_FOLDWORD)\n\t {\n\t\tif (mip->mi_cend != mip->mi_word + wlen)\n\t\t{\n\t\t // mi_capflags was set for a different word length, need\n\t\t // to do it again.\n\t\t mip->mi_cend = mip->mi_word + wlen;\n\t\t mip->mi_capflags = captype(mip->mi_word, mip->mi_cend);\n\t\t}",
"\t\tif (mip->mi_capflags == WF_KEEPCAP\n\t\t\t\t|| !spell_valid_case(mip->mi_capflags, flags))\n\t\t continue;\n\t }",
"\t // When mode is FIND_PREFIX the word must support the prefix:\n\t // check the prefix ID and the condition. Do that for the list at\n\t // mip->mi_prefarridx that find_prefix() filled.\n\t else if (mode == FIND_PREFIX && !prefix_found)\n\t {\n\t\tc = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx,\n\t\t\t\t flags,\n\t\t\t\t mip->mi_word + mip->mi_cprefixlen, slang,\n\t\t\t\t FALSE);\n\t\tif (c == 0)\n\t\t continue;",
"\t\t// Use the WF_RARE flag for a rare prefix.\n\t\tif (c & WF_RAREPFX)\n\t\t flags |= WF_RARE;\n\t\tprefix_found = TRUE;\n\t }",
"\t if (slang->sl_nobreak)\n\t {\n\t\tif ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND)\n\t\t\t&& (flags & WF_BANNED) == 0)\n\t\t{\n\t\t // NOBREAK: found a valid following word. That's all we\n\t\t // need to know, so return.\n\t\t mip->mi_result = SP_OK;\n\t\t break;\n\t\t}\n\t }",
"\t else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND\n\t\t\t\t\t\t\t\t|| !word_ends))\n\t {\n\t\t// If there is no compound flag or the word is shorter than\n\t\t// COMPOUNDMIN reject it quickly.\n\t\t// Makes you wonder why someone puts a compound flag on a word\n\t\t// that's too short... Myspell compatibility requires this\n\t\t// anyway.\n\t\tif (((unsigned)flags >> 24) == 0\n\t\t\t || wlen - mip->mi_compoff < slang->sl_compminlen)\n\t\t continue;\n\t\t// For multi-byte chars check character length against\n\t\t// COMPOUNDMIN.\n\t\tif (has_mbyte\n\t\t\t&& slang->sl_compminlen > 0\n\t\t\t&& mb_charlen_len(mip->mi_word + mip->mi_compoff,\n\t\t\t\twlen - mip->mi_compoff) < slang->sl_compminlen)\n\t\t\tcontinue;",
"\t\t// Limit the number of compound words to COMPOUNDWORDMAX if no\n\t\t// maximum for syllables is specified.\n\t\tif (!word_ends && mip->mi_complen + mip->mi_compextra + 2\n\t\t\t\t\t\t\t > slang->sl_compmax\n\t\t\t\t\t && slang->sl_compsylmax == MAXWLEN)\n\t\t continue;",
"\t\t// Don't allow compounding on a side where an affix was added,\n\t\t// unless COMPOUNDPERMITFLAG was used.\n\t\tif (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF))\n\t\t continue;\n\t\tif (!word_ends && (flags & WF_NOCOMPAFT))\n\t\t continue;",
"\t\t// Quickly check if compounding is possible with this flag.\n\t\tif (!byte_in_str(mip->mi_complen == 0\n\t\t\t\t\t? slang->sl_compstartflags\n\t\t\t\t\t: slang->sl_compallflags,\n\t\t\t\t\t ((unsigned)flags >> 24)))\n\t\t continue;",
"\t\t// If there is a match with a CHECKCOMPOUNDPATTERN rule\n\t\t// discard the compound word.\n\t\tif (match_checkcompoundpattern(ptr, wlen, &slang->sl_comppat))\n\t\t continue;",
"\t\tif (mode == FIND_COMPOUND)\n\t\t{\n\t\t int\t capflags;",
"\t\t // Need to check the caps type of the appended compound\n\t\t // word.\n\t\t if (has_mbyte && STRNCMP(ptr, mip->mi_word,\n\t\t\t\t\t\t\tmip->mi_compoff) != 0)\n\t\t {\n\t\t\t// case folding may have changed the length\n\t\t\tp = mip->mi_word;\n\t\t\tfor (s = ptr; s < ptr + mip->mi_compoff; MB_PTR_ADV(s))\n\t\t\t MB_PTR_ADV(p);\n\t\t }\n\t\t else\n\t\t\tp = mip->mi_word + mip->mi_compoff;\n\t\t capflags = captype(p, mip->mi_word + wlen);\n\t\t if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP\n\t\t\t\t\t\t && (flags & WF_FIXCAP) != 0))\n\t\t\tcontinue;",
"\t\t if (capflags != WF_ALLCAP)\n\t\t {\n\t\t\t// When the character before the word is a word\n\t\t\t// character we do not accept a Onecap word. We do\n\t\t\t// accept a no-caps word, even when the dictionary\n\t\t\t// word specifies ONECAP.\n\t\t\tMB_PTR_BACK(mip->mi_word, p);\n\t\t\tif (spell_iswordp_nmw(p, mip->mi_win)\n\t\t\t\t? capflags == WF_ONECAP\n\t\t\t\t: (flags & WF_ONECAP) != 0\n\t\t\t\t\t\t && capflags != WF_ONECAP)\n\t\t\t continue;\n\t\t }\n\t\t}",
"\t\t// If the word ends the sequence of compound flags of the\n\t\t// words must match with one of the COMPOUNDRULE items and\n\t\t// the number of syllables must not be too large.\n\t\tmip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24);\n\t\tmip->mi_compflags[mip->mi_complen + 1] = NUL;\n\t\tif (word_ends)\n\t\t{\n\t\t char_u\tfword[MAXWLEN];",
"\t\t if (slang->sl_compsylmax < MAXWLEN)\n\t\t {\n\t\t\t// \"fword\" is only needed for checking syllables.\n\t\t\tif (ptr == mip->mi_word)\n\t\t\t (void)spell_casefold(mip->mi_win,\n\t\t\t\t\t\t ptr, wlen, fword, MAXWLEN);\n\t\t\telse\n\t\t\t vim_strncpy(fword, ptr, endlen[endidxcnt]);\n\t\t }\n\t\t if (!can_compound(slang, fword, mip->mi_compflags))\n\t\t\tcontinue;\n\t\t}\n\t\telse if (slang->sl_comprules != NULL\n\t\t\t && !match_compoundrule(slang, mip->mi_compflags))\n\t\t // The compound flags collected so far do not match any\n\t\t // COMPOUNDRULE, discard the compounded word.\n\t\t continue;\n\t }",
"\t // Check NEEDCOMPOUND: can't use word without compounding.\n\t else if (flags & WF_NEEDCOMP)\n\t\tcontinue;",
"\t nobreak_result = SP_OK;",
"\t if (!word_ends)\n\t {\n\t\tint\tsave_result = mip->mi_result;\n\t\tchar_u\t*save_end = mip->mi_end;\n\t\tlangp_T\t*save_lp = mip->mi_lp;\n\t\tint\tlpi;",
"\t\t// Check that a valid word follows. If there is one and we\n\t\t// are compounding, it will set \"mi_result\", thus we are\n\t\t// always finished here. For NOBREAK we only check that a\n\t\t// valid word follows.\n\t\t// Recursive!\n\t\tif (slang->sl_nobreak)\n\t\t mip->mi_result = SP_BAD;",
"\t\t// Find following word in case-folded tree.\n\t\tmip->mi_compoff = endlen[endidxcnt];\n\t\tif (has_mbyte && mode == FIND_KEEPWORD)\n\t\t{\n\t\t // Compute byte length in case-folded word from \"wlen\":\n\t\t // byte length in keep-case word. Length may change when\n\t\t // folding case. This can be slow, take a shortcut when\n\t\t // the case-folded word is equal to the keep-case word.\n\t\t p = mip->mi_fword;\n\t\t if (STRNCMP(ptr, p, wlen) != 0)\n\t\t {\n\t\t\tfor (s = ptr; s < ptr + wlen; MB_PTR_ADV(s))\n\t\t\t MB_PTR_ADV(p);\n\t\t\tmip->mi_compoff = (int)(p - mip->mi_fword);\n\t\t }\n\t\t}\n#if 0 // Disabled, see below\n\t\tc = mip->mi_compoff;\n#endif\n\t\t++mip->mi_complen;\n\t\tif (flags & WF_COMPROOT)\n\t\t ++mip->mi_compextra;",
"\t\t// For NOBREAK we need to try all NOBREAK languages, at least\n\t\t// to find the \".add\" file(s).\n\t\tfor (lpi = 0; lpi < mip->mi_win->w_s->b_langp.ga_len; ++lpi)\n\t\t{\n\t\t if (slang->sl_nobreak)\n\t\t {\n\t\t\tmip->mi_lp = LANGP_ENTRY(mip->mi_win->w_s->b_langp, lpi);\n\t\t\tif (mip->mi_lp->lp_slang->sl_fidxs == NULL\n\t\t\t\t\t || !mip->mi_lp->lp_slang->sl_nobreak)\n\t\t\t continue;\n\t\t }",
"\t\t find_word(mip, FIND_COMPOUND);",
"\t\t // When NOBREAK any word that matches is OK. Otherwise we\n\t\t // need to find the longest match, thus try with keep-case\n\t\t // and prefix too.\n\t\t if (!slang->sl_nobreak || mip->mi_result == SP_BAD)\n\t\t {\n\t\t\t// Find following word in keep-case tree.\n\t\t\tmip->mi_compoff = wlen;\n\t\t\tfind_word(mip, FIND_KEEPCOMPOUND);",
"#if 0\t // Disabled, a prefix must not appear halfway a compound word,\n\t // unless the COMPOUNDPERMITFLAG is used and then it can't be a\n\t // postponed prefix.\n\t\t\tif (!slang->sl_nobreak || mip->mi_result == SP_BAD)\n\t\t\t{\n\t\t\t // Check for following word with prefix.\n\t\t\t mip->mi_compoff = c;\n\t\t\t find_prefix(mip, FIND_COMPOUND);\n\t\t\t}\n#endif\n\t\t }",
"\t\t if (!slang->sl_nobreak)\n\t\t\tbreak;\n\t\t}\n\t\t--mip->mi_complen;\n\t\tif (flags & WF_COMPROOT)\n\t\t --mip->mi_compextra;\n\t\tmip->mi_lp = save_lp;",
"\t\tif (slang->sl_nobreak)\n\t\t{\n\t\t nobreak_result = mip->mi_result;\n\t\t mip->mi_result = save_result;\n\t\t mip->mi_end = save_end;\n\t\t}\n\t\telse\n\t\t{\n\t\t if (mip->mi_result == SP_OK)\n\t\t\tbreak;\n\t\t continue;\n\t\t}\n\t }",
"\t if (flags & WF_BANNED)\n\t\tres = SP_BANNED;\n\t else if (flags & WF_REGION)\n\t {\n\t\t// Check region.\n\t\tif ((mip->mi_lp->lp_region & (flags >> 16)) != 0)\n\t\t res = SP_OK;\n\t\telse\n\t\t res = SP_LOCAL;\n\t }\n\t else if (flags & WF_RARE)\n\t\tres = SP_RARE;\n\t else\n\t\tres = SP_OK;",
"\t // Always use the longest match and the best result. For NOBREAK\n\t // we separately keep the longest match without a following good\n\t // word as a fall-back.\n\t if (nobreak_result == SP_BAD)\n\t {\n\t\tif (mip->mi_result2 > res)\n\t\t{\n\t\t mip->mi_result2 = res;\n\t\t mip->mi_end2 = mip->mi_word + wlen;\n\t\t}\n\t\telse if (mip->mi_result2 == res\n\t\t\t\t\t&& mip->mi_end2 < mip->mi_word + wlen)\n\t\t mip->mi_end2 = mip->mi_word + wlen;\n\t }\n\t else if (mip->mi_result > res)\n\t {\n\t\tmip->mi_result = res;\n\t\tmip->mi_end = mip->mi_word + wlen;\n\t }\n\t else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen)\n\t\tmip->mi_end = mip->mi_word + wlen;",
"\t if (mip->mi_result == SP_OK)\n\t\tbreak;\n\t}",
"\tif (mip->mi_result == SP_OK)\n\t break;\n }\n}",
"/*\n * Return TRUE if there is a match between the word ptr[wlen] and\n * CHECKCOMPOUNDPATTERN rules, assuming that we will concatenate with another\n * word.\n * A match means that the first part of CHECKCOMPOUNDPATTERN matches at the\n * end of ptr[wlen] and the second part matches after it.\n */\n int\nmatch_checkcompoundpattern(\n char_u\t*ptr,\n int\t\twlen,\n garray_T\t*gap) // &sl_comppat\n{\n int\t\ti;\n char_u\t*p;\n int\t\tlen;",
" for (i = 0; i + 1 < gap->ga_len; i += 2)\n {\n\tp = ((char_u **)gap->ga_data)[i + 1];\n\tif (STRNCMP(ptr + wlen, p, STRLEN(p)) == 0)\n\t{\n\t // Second part matches at start of following compound word, now\n\t // check if first part matches at end of previous word.\n\t p = ((char_u **)gap->ga_data)[i];\n\t len = (int)STRLEN(p);\n\t if (len <= wlen && STRNCMP(ptr + wlen - len, p, len) == 0)\n\t\treturn TRUE;\n\t}\n }\n return FALSE;\n}",
"/*\n * Return TRUE if \"flags\" is a valid sequence of compound flags and \"word\"\n * does not have too many syllables.\n */\n int\ncan_compound(slang_T *slang, char_u *word, char_u *flags)\n{\n char_u\tuflags[MAXWLEN * 2];\n int\t\ti;\n char_u\t*p;",
" if (slang->sl_compprog == NULL)\n\treturn FALSE;\n if (enc_utf8)\n {\n\t// Need to convert the single byte flags to utf8 characters.\n\tp = uflags;\n\tfor (i = 0; flags[i] != NUL; ++i)\n\t p += utf_char2bytes(flags[i], p);\n\t*p = NUL;\n\tp = uflags;\n }\n else\n\tp = flags;\n if (!vim_regexec_prog(&slang->sl_compprog, FALSE, p, 0))\n\treturn FALSE;",
" // Count the number of syllables. This may be slow, do it last. If there\n // are too many syllables AND the number of compound words is above\n // COMPOUNDWORDMAX then compounding is not allowed.\n if (slang->sl_compsylmax < MAXWLEN\n\t\t && count_syllables(slang, word) > slang->sl_compsylmax)\n\treturn (int)STRLEN(flags) < slang->sl_compmax;\n return TRUE;\n}",
"/*\n * Return TRUE if the compound flags in compflags[] match the start of any\n * compound rule. This is used to stop trying a compound if the flags\n * collected so far can't possibly match any compound rule.\n * Caller must check that slang->sl_comprules is not NULL.\n */\n int\nmatch_compoundrule(slang_T *slang, char_u *compflags)\n{\n char_u\t*p;\n int\t\ti;\n int\t\tc;",
" // loop over all the COMPOUNDRULE entries\n for (p = slang->sl_comprules; *p != NUL; ++p)\n {\n\t// loop over the flags in the compound word we have made, match\n\t// them against the current rule entry\n\tfor (i = 0; ; ++i)\n\t{\n\t c = compflags[i];\n\t if (c == NUL)\n\t\t// found a rule that matches for the flags we have so far\n\t\treturn TRUE;\n\t if (*p == '/' || *p == NUL)\n\t\tbreak; // end of rule, it's too short\n\t if (*p == '[')\n\t {\n\t\tint match = FALSE;",
"\t\t// compare against all the flags in []\n\t\t++p;\n\t\twhile (*p != ']' && *p != NUL)\n\t\t if (*p++ == c)\n\t\t\tmatch = TRUE;\n\t\tif (!match)\n\t\t break; // none matches\n\t }\n\t else if (*p != c)\n\t\tbreak; // flag of word doesn't match flag in pattern\n\t ++p;\n\t}",
"\t// Skip to the next \"/\", where the next pattern starts.\n\tp = vim_strchr(p, '/');\n\tif (p == NULL)\n\t break;\n }",
" // Checked all the rules and none of them match the flags, so there\n // can't possibly be a compound starting with these flags.\n return FALSE;\n}",
"/*\n * Return non-zero if the prefix indicated by \"arridx\" matches with the prefix\n * ID in \"flags\" for the word \"word\".\n * The WF_RAREPFX flag is included in the return value for a rare prefix.\n */\n int\nvalid_word_prefix(\n int\t\ttotprefcnt,\t// nr of prefix IDs\n int\t\tarridx,\t\t// idx in sl_pidxs[]\n int\t\tflags,\n char_u\t*word,\n slang_T\t*slang,\n int\t\tcond_req)\t// only use prefixes with a condition\n{\n int\t\tprefcnt;\n int\t\tpidx;\n regprog_T\t**rp;\n int\t\tprefid;",
" prefid = (unsigned)flags >> 24;\n for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt)\n {\n\tpidx = slang->sl_pidxs[arridx + prefcnt];",
"\t// Check the prefix ID.\n\tif (prefid != (pidx & 0xff))\n\t continue;",
"\t// Check if the prefix doesn't combine and the word already has a\n\t// suffix.\n\tif ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC))\n\t continue;",
"\t// Check the condition, if there is one. The condition index is\n\t// stored in the two bytes above the prefix ID byte.\n\trp = &slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff];\n\tif (*rp != NULL)\n\t{\n\t if (!vim_regexec_prog(rp, FALSE, word, 0))\n\t\tcontinue;\n\t}\n\telse if (cond_req)\n\t continue;",
"\t// It's a match! Return the WF_ flags.\n\treturn pidx;\n }\n return 0;\n}",
"/*\n * Check if the word at \"mip->mi_word\" has a matching prefix.\n * If it does, then check the following word.\n *\n * If \"mode\" is \"FIND_COMPOUND\" then do the same after another word, find a\n * prefix in a compound word.\n *\n * For a match mip->mi_result is updated.\n */\n static void\nfind_prefix(matchinf_T *mip, int mode)\n{\n idx_T\tarridx = 0;\n int\t\tlen;\n int\t\twlen = 0;\n int\t\tflen;\n int\t\tc;\n char_u\t*ptr;\n idx_T\tlo, hi, m;\n slang_T\t*slang = mip->mi_lp->lp_slang;\n char_u\t*byts;\n idx_T\t*idxs;",
" byts = slang->sl_pbyts;\n if (byts == NULL)\n\treturn;\t\t\t// array is empty",
" // We use the case-folded word here, since prefixes are always\n // case-folded.\n ptr = mip->mi_fword;\n flen = mip->mi_fwordlen; // available case-folded bytes\n if (mode == FIND_COMPOUND)\n {\n\t// Skip over the previously found word(s).\n\tptr += mip->mi_compoff;\n\tflen -= mip->mi_compoff;\n }\n idxs = slang->sl_pidxs;",
" /*\n * Repeat advancing in the tree until:\n * - there is a byte that doesn't match,\n * - we reach the end of the tree,\n * - or we reach the end of the line.\n */\n for (;;)\n {\n\tif (flen == 0 && *mip->mi_fend != NUL)\n\t flen = fold_more(mip);",
"\tlen = byts[arridx++];",
"\t// If the first possible byte is a zero the prefix could end here.\n\t// Check if the following word matches and supports the prefix.\n\tif (byts[arridx] == 0)\n\t{\n\t // There can be several prefixes with different conditions. We\n\t // try them all, since we don't know which one will give the\n\t // longest match. The word is the same each time, pass the list\n\t // of possible prefixes to find_word().\n\t mip->mi_prefarridx = arridx;\n\t mip->mi_prefcnt = len;\n\t while (len > 0 && byts[arridx] == 0)\n\t {\n\t\t++arridx;\n\t\t--len;\n\t }\n\t mip->mi_prefcnt -= len;",
"\t // Find the word that comes after the prefix.\n\t mip->mi_prefixlen = wlen;\n\t if (mode == FIND_COMPOUND)\n\t\t// Skip over the previously found word(s).\n\t\tmip->mi_prefixlen += mip->mi_compoff;",
"\t if (has_mbyte)\n\t {\n\t\t// Case-folded length may differ from original length.\n\t\tmip->mi_cprefixlen = nofold_len(mip->mi_fword,\n\t\t\t\t\t mip->mi_prefixlen, mip->mi_word);\n\t }\n\t else\n\t\tmip->mi_cprefixlen = mip->mi_prefixlen;\n\t find_word(mip, FIND_PREFIX);",
"\n\t if (len == 0)\n\t\tbreak;\t // no children, word must end here\n\t}",
"\t// Stop looking at end of the line.\n\tif (ptr[wlen] == NUL)\n\t break;",
"\t// Perform a binary search in the list of accepted bytes.\n\tc = ptr[wlen];\n\tlo = arridx;\n\thi = arridx + len - 1;\n\twhile (lo < hi)\n\t{\n\t m = (lo + hi) / 2;\n\t if (byts[m] > c)\n\t\thi = m - 1;\n\t else if (byts[m] < c)\n\t\tlo = m + 1;\n\t else\n\t {\n\t\tlo = hi = m;\n\t\tbreak;\n\t }\n\t}",
"\t// Stop if there is no matching byte.\n\tif (hi < lo || byts[lo] != c)\n\t break;",
"\t// Continue at the child (if there is one).\n\tarridx = idxs[lo];\n\t++wlen;\n\t--flen;\n }\n}",
"/*\n * Need to fold at least one more character. Do until next non-word character\n * for efficiency. Include the non-word character too.\n * Return the length of the folded chars in bytes.\n */\n static int\nfold_more(matchinf_T *mip)\n{\n int\t\tflen;\n char_u\t*p;",
" p = mip->mi_fend;\n do\n\tMB_PTR_ADV(mip->mi_fend);\n while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_win));",
" // Include the non-word character so that we can check for the word end.\n if (*mip->mi_fend != NUL)\n\tMB_PTR_ADV(mip->mi_fend);",
" (void)spell_casefold(mip->mi_win, p, (int)(mip->mi_fend - p),\n\t\t\t mip->mi_fword + mip->mi_fwordlen,\n\t\t\t MAXWLEN - mip->mi_fwordlen);\n flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen);\n mip->mi_fwordlen += flen;\n return flen;\n}",
"/*\n * Check case flags for a word. Return TRUE if the word has the requested\n * case.\n */\n int\nspell_valid_case(\n int\t wordflags,\t // flags for the checked word.\n int\t treeflags)\t // flags for the word in the spell tree\n{\n return ((wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0)\n\t || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0\n\t\t&& ((treeflags & WF_ONECAP) == 0\n\t\t\t\t\t || (wordflags & WF_ONECAP) != 0)));\n}",
"/*\n * Return TRUE if spell checking is not enabled.\n */\n static int\nno_spell_checking(win_T *wp)\n{\n if (!wp->w_p_spell || *wp->w_s->b_p_spl == NUL\n\t\t\t\t\t || wp->w_s->b_langp.ga_len == 0)\n {\n\temsg(_(e_spell_checking_is_not_possible));\n\treturn TRUE;\n }\n return FALSE;\n}",
"/*\n * Move to next spell error.\n * \"curline\" is FALSE for \"[s\", \"]s\", \"[S\" and \"]S\".\n * \"curline\" is TRUE to find word under/after cursor in the same line.\n * For Insert mode completion \"dir\" is BACKWARD and \"curline\" is TRUE: move\n * to after badly spelled word before the cursor.\n * Return 0 if not found, length of the badly spelled word otherwise.\n */\n int\nspell_move_to(\n win_T\t*wp,\n int\t\tdir,\t\t// FORWARD or BACKWARD\n int\t\tallwords,\t// TRUE for \"[s\"/\"]s\", FALSE for \"[S\"/\"]S\"\n int\t\tcurline,\n hlf_T\t*attrp)\t\t// return: attributes of bad word or NULL\n\t\t\t\t// (only when \"dir\" is FORWARD)\n{\n linenr_T\tlnum;\n pos_T\tfound_pos;\n int\t\tfound_len = 0;\n char_u\t*line;\n char_u\t*p;\n char_u\t*endp;",
" hlf_T\tattr;",
" int\t\tlen;\n#ifdef FEAT_SYN_HL\n int\t\thas_syntax = syntax_present(wp);\n#endif\n int\t\tcol;\n int\t\tcan_spell;\n char_u\t*buf = NULL;\n int\t\tbuflen = 0;\n int\t\tskip = 0;\n int\t\tcapcol = -1;\n int\t\tfound_one = FALSE;\n int\t\twrapped = FALSE;",
" if (no_spell_checking(wp))\n\treturn 0;",
" /*\n * Start looking for bad word at the start of the line, because we can't\n * start halfway a word, we don't know where it starts or ends.\n *\n * When searching backwards, we continue in the line to find the last\n * bad word (in the cursor line: before the cursor).\n *\n * We concatenate the start of the next line, so that wrapped words work\n * (e.g. \"et<line-break>cetera\"). Doesn't work when searching backwards\n * though...\n */\n lnum = wp->w_cursor.lnum;\n CLEAR_POS(&found_pos);",
" while (!got_int)\n {",
"",
"\tline = ml_get_buf(wp->w_buffer, lnum, FALSE);",
"\tlen = (int)STRLEN(line);\n\tif (buflen < len + MAXWLEN + 2)\n\t{\n\t vim_free(buf);\n\t buflen = len + MAXWLEN + 2;\n\t buf = alloc(buflen);\n\t if (buf == NULL)\n\t\tbreak;\n\t}",
"\t// In first line check first word for Capital.\n\tif (lnum == 1)\n\t capcol = 0;",
"\t// For checking first word with a capital skip white space.\n\tif (capcol == 0)\n\t capcol = getwhitecols(line);\n\telse if (curline && wp == curwin)\n\t{\n\t // For spellbadword(): check if first word needs a capital.\n\t col = getwhitecols(line);\n\t if (check_need_cap(lnum, col))\n\t\tcapcol = col;",
"\t // Need to get the line again, may have looked at the previous\n\t // one.\n\t line = ml_get_buf(wp->w_buffer, lnum, FALSE);\n\t}",
"\t// Copy the line into \"buf\" and append the start of the next line if",
"\t// possible.",
"\tSTRCPY(buf, line);\n\tif (lnum < wp->w_buffer->b_ml.ml_line_count)\n\t spell_cat_line(buf + STRLEN(buf),\n\t\t\t ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN);",
"\tp = buf + skip;\n\tendp = buf + len;\n\twhile (p < endp)\n\t{\n\t // When searching backward don't search after the cursor. Unless\n\t // we wrapped around the end of the buffer.\n\t if (dir == BACKWARD\n\t\t && lnum == wp->w_cursor.lnum\n\t\t && !wrapped\n\t\t && (colnr_T)(p - buf) >= wp->w_cursor.col)\n\t\tbreak;",
"\t // start of word\n\t attr = HLF_COUNT;\n\t len = spell_check(wp, p, &attr, &capcol, FALSE);",
"\t if (attr != HLF_COUNT)\n\t {\n\t\t// We found a bad word. Check the attribute.\n\t\tif (allwords || attr == HLF_SPB)\n\t\t{\n\t\t // When searching forward only accept a bad word after\n\t\t // the cursor.\n\t\t if (dir == BACKWARD\n\t\t\t || lnum != wp->w_cursor.lnum\n\t\t\t || (wrapped\n\t\t\t\t|| (colnr_T)(curline ? p - buf + len\n\t\t\t\t\t\t : p - buf)\n\t\t\t\t\t\t > wp->w_cursor.col))\n\t\t {\n#ifdef FEAT_SYN_HL\n\t\t\tif (has_syntax)\n\t\t\t{\n\t\t\t col = (int)(p - buf);\n\t\t\t (void)syn_get_id(wp, lnum, (colnr_T)col,\n\t\t\t\t\t\t FALSE, &can_spell, FALSE);\n\t\t\t if (!can_spell)\n\t\t\t\tattr = HLF_COUNT;\n\t\t\t}\n\t\t\telse\n#endif\n\t\t\t can_spell = TRUE;",
"\t\t\tif (can_spell)\n\t\t\t{\n\t\t\t found_one = TRUE;\n\t\t\t found_pos.lnum = lnum;\n\t\t\t found_pos.col = (int)(p - buf);\n\t\t\t found_pos.coladd = 0;\n\t\t\t if (dir == FORWARD)\n\t\t\t {\n\t\t\t\t// No need to search further.\n\t\t\t\twp->w_cursor = found_pos;\n\t\t\t\tvim_free(buf);\n\t\t\t\tif (attrp != NULL)\n\t\t\t\t *attrp = attr;\n\t\t\t\treturn len;\n\t\t\t }\n\t\t\t else if (curline)\n\t\t\t\t// Insert mode completion: put cursor after\n\t\t\t\t// the bad word.\n\t\t\t\tfound_pos.col += len;\n\t\t\t found_len = len;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\tfound_one = TRUE;\n\t\t}\n\t }",
"\t // advance to character after the word\n\t p += len;\n\t capcol -= len;\n\t}",
"\tif (dir == BACKWARD && found_pos.lnum != 0)\n\t{\n\t // Use the last match in the line (before the cursor).\n\t wp->w_cursor = found_pos;\n\t vim_free(buf);\n\t return found_len;\n\t}",
"\tif (curline)\n\t break;\t// only check cursor line",
"\t// If we are back at the starting line and searched it again there\n\t// is no match, give up.\n\tif (lnum == wp->w_cursor.lnum && wrapped)\n\t break;",
"\t// Advance to next line.\n\tif (dir == BACKWARD)\n\t{\n\t if (lnum > 1)\n\t\t--lnum;\n\t else if (!p_ws)\n\t\tbreak;\t // at first line and 'nowrapscan'\n\t else\n\t {\n\t\t// Wrap around to the end of the buffer. May search the\n\t\t// starting line again and accept the last match.\n\t\tlnum = wp->w_buffer->b_ml.ml_line_count;\n\t\twrapped = TRUE;\n\t\tif (!shortmess(SHM_SEARCH))\n\t\t give_warning((char_u *)_(top_bot_msg), TRUE);\n\t }\n\t capcol = -1;\n\t}\n\telse\n\t{\n\t if (lnum < wp->w_buffer->b_ml.ml_line_count)\n\t\t++lnum;\n\t else if (!p_ws)\n\t\tbreak;\t // at first line and 'nowrapscan'\n\t else\n\t {\n\t\t// Wrap around to the start of the buffer. May search the\n\t\t// starting line again and accept the first match.\n\t\tlnum = 1;\n\t\twrapped = TRUE;\n\t\tif (!shortmess(SHM_SEARCH))\n\t\t give_warning((char_u *)_(bot_top_msg), TRUE);\n\t }",
"\t // If we are back at the starting line and there is no match then\n\t // give up.\n\t if (lnum == wp->w_cursor.lnum && !found_one)\n\t\tbreak;",
"\t // Skip the characters at the start of the next line that were\n\t // included in a match crossing line boundaries.\n\t if (attr == HLF_COUNT)\n\t\tskip = (int)(p - endp);\n\t else\n\t\tskip = 0;",
"\t // Capcol skips over the inserted space.\n\t --capcol;",
"\t // But after empty line check first word in next line",
"\t if (*skipwhite(line) == NUL)",
"\t\tcapcol = 0;\n\t}",
"\tline_breakcheck();\n }",
" vim_free(buf);\n return 0;\n}",
"/*\n * For spell checking: concatenate the start of the following line \"line\" into\n * \"buf\", blanking-out special characters. Copy less than \"maxlen\" bytes.\n * Keep the blanks at the start of the next line, this is used in win_line()\n * to skip those bytes if the word was OK.\n */\n void\nspell_cat_line(char_u *buf, char_u *line, int maxlen)\n{\n char_u\t*p;\n int\t\tn;",
" p = skipwhite(line);\n while (vim_strchr((char_u *)\"*#/\\\"\\t\", *p) != NULL)\n\tp = skipwhite(p + 1);",
" if (*p != NUL)\n {\n\t// Only worth concatenating if there is something else than spaces to\n\t// concatenate.\n\tn = (int)(p - line) + 1;\n\tif (n < maxlen - 1)\n\t{\n\t vim_memset(buf, ' ', n);\n\t vim_strncpy(buf + n, p, maxlen - 1 - n);\n\t}\n }\n}",
"/*\n * Structure used for the cookie argument of do_in_runtimepath().\n */\ntypedef struct spelload_S\n{\n char_u sl_lang[MAXWLEN + 1];\t// language name\n slang_T *sl_slang;\t\t\t// resulting slang_T struct\n int\t sl_nobreak;\t\t\t// NOBREAK language found\n} spelload_T;",
"/*\n * Load word list(s) for \"lang\" from Vim spell file(s).\n * \"lang\" must be the language without the region: e.g., \"en\".\n */\n static void\nspell_load_lang(char_u *lang)\n{\n char_u\tfname_enc[85];\n int\t\tr;\n spelload_T\tsl;\n int\t\tround;",
" // Copy the language name to pass it to spell_load_cb() as a cookie.\n // It's truncated when an error is detected.\n STRCPY(sl.sl_lang, lang);\n sl.sl_slang = NULL;\n sl.sl_nobreak = FALSE;",
" // We may retry when no spell file is found for the language, an\n // autocommand may load it then.\n for (round = 1; round <= 2; ++round)\n {\n\t/*\n\t * Find the first spell file for \"lang\" in 'runtimepath' and load it.\n\t */\n\tvim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,\n#ifdef VMS\n\t\t\t\t\t\"spell/%s_%s.spl\",\n#else\n\t\t\t\t\t\"spell/%s.%s.spl\",\n#endif\n\t\t\t\t\t\t\t lang, spell_enc());\n\tr = do_in_runtimepath(fname_enc, 0, spell_load_cb, &sl);",
"\tif (r == FAIL && *sl.sl_lang != NUL)\n\t{\n\t // Try loading the ASCII version.\n\t vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,\n#ifdef VMS\n\t\t\t\t\t\t \"spell/%s_ascii.spl\",\n#else\n\t\t\t\t\t\t \"spell/%s.ascii.spl\",\n#endif\n\t\t\t\t\t\t\t\t\tlang);\n\t r = do_in_runtimepath(fname_enc, 0, spell_load_cb, &sl);",
"\t if (r == FAIL && *sl.sl_lang != NUL && round == 1\n\t\t && apply_autocmds(EVENT_SPELLFILEMISSING, lang,\n\t\t\t\t\t curbuf->b_fname, FALSE, curbuf))\n\t\tcontinue;\n\t break;\n\t}\n\tbreak;\n }",
" if (r == FAIL)\n {\n\tsmsg(\n#ifdef VMS\n\t_(\"Warning: Cannot find word list \\\"%s_%s.spl\\\" or \\\"%s_ascii.spl\\\"\"),\n#else\n\t_(\"Warning: Cannot find word list \\\"%s.%s.spl\\\" or \\\"%s.ascii.spl\\\"\"),\n#endif\n\t\t\t\t\t\t lang, spell_enc(), lang);\n }\n else if (sl.sl_slang != NULL)\n {\n\t// At least one file was loaded, now load ALL the additions.\n\tSTRCPY(fname_enc + STRLEN(fname_enc) - 3, \"add.spl\");\n\tdo_in_runtimepath(fname_enc, DIP_ALL, spell_load_cb, &sl);\n }\n}",
"/*\n * Return the encoding used for spell checking: Use 'encoding', except that we\n * use \"latin1\" for \"latin9\". And limit to 60 characters (just in case).\n */\n char_u *\nspell_enc(void)\n{",
" if (STRLEN(p_enc) < 60 && STRCMP(p_enc, \"iso-8859-15\") != 0)\n\treturn p_enc;\n return (char_u *)\"latin1\";\n}",
"/*\n * Get the name of the .spl file for the internal wordlist into\n * \"fname[MAXPATHL]\".\n */\n static void\nint_wordlist_spl(char_u *fname)\n{\n vim_snprintf((char *)fname, MAXPATHL, SPL_FNAME_TMPL,\n\t\t\t\t\t\t int_wordlist, spell_enc());\n}",
"/*\n * Allocate a new slang_T for language \"lang\". \"lang\" can be NULL.\n * Caller must fill \"sl_next\".\n */\n slang_T *\nslang_alloc(char_u *lang)\n{\n slang_T *lp;",
" lp = ALLOC_CLEAR_ONE(slang_T);\n if (lp != NULL)\n {\n\tif (lang != NULL)\n\t lp->sl_name = vim_strsave(lang);\n\tga_init2(&lp->sl_rep, sizeof(fromto_T), 10);\n\tga_init2(&lp->sl_repsal, sizeof(fromto_T), 10);\n\tlp->sl_compmax = MAXWLEN;\n\tlp->sl_compsylmax = MAXWLEN;\n\thash_init(&lp->sl_wordcount);\n }",
" return lp;\n}",
"/*\n * Free the contents of an slang_T and the structure itself.\n */\n void\nslang_free(slang_T *lp)\n{\n vim_free(lp->sl_name);\n vim_free(lp->sl_fname);\n slang_clear(lp);\n vim_free(lp);\n}",
"/*\n * Clear an slang_T so that the file can be reloaded.\n */\n void\nslang_clear(slang_T *lp)\n{\n garray_T\t*gap;\n fromto_T\t*ftp;\n salitem_T\t*smp;\n int\t\ti;\n int\t\tround;",
" VIM_CLEAR(lp->sl_fbyts);\n VIM_CLEAR(lp->sl_kbyts);\n VIM_CLEAR(lp->sl_pbyts);",
" VIM_CLEAR(lp->sl_fidxs);\n VIM_CLEAR(lp->sl_kidxs);\n VIM_CLEAR(lp->sl_pidxs);",
" for (round = 1; round <= 2; ++round)\n {\n\tgap = round == 1 ? &lp->sl_rep : &lp->sl_repsal;\n\twhile (gap->ga_len > 0)\n\t{\n\t ftp = &((fromto_T *)gap->ga_data)[--gap->ga_len];\n\t vim_free(ftp->ft_from);\n\t vim_free(ftp->ft_to);\n\t}\n\tga_clear(gap);\n }",
" gap = &lp->sl_sal;\n if (lp->sl_sofo)\n {\n\t// \"ga_len\" is set to 1 without adding an item for latin1\n\tif (gap->ga_data != NULL)\n\t // SOFOFROM and SOFOTO items: free lists of wide characters.\n\t for (i = 0; i < gap->ga_len; ++i)\n\t\tvim_free(((int **)gap->ga_data)[i]);\n }\n else\n\t// SAL items: free salitem_T items\n\twhile (gap->ga_len > 0)\n\t{\n\t smp = &((salitem_T *)gap->ga_data)[--gap->ga_len];\n\t vim_free(smp->sm_lead);\n\t // Don't free sm_oneof and sm_rules, they point into sm_lead.\n\t vim_free(smp->sm_to);\n\t vim_free(smp->sm_lead_w);\n\t vim_free(smp->sm_oneof_w);\n\t vim_free(smp->sm_to_w);\n\t}\n ga_clear(gap);",
" for (i = 0; i < lp->sl_prefixcnt; ++i)\n\tvim_regfree(lp->sl_prefprog[i]);\n lp->sl_prefixcnt = 0;\n VIM_CLEAR(lp->sl_prefprog);",
" VIM_CLEAR(lp->sl_info);",
" VIM_CLEAR(lp->sl_midword);",
" vim_regfree(lp->sl_compprog);\n lp->sl_compprog = NULL;\n VIM_CLEAR(lp->sl_comprules);\n VIM_CLEAR(lp->sl_compstartflags);\n VIM_CLEAR(lp->sl_compallflags);",
" VIM_CLEAR(lp->sl_syllable);\n ga_clear(&lp->sl_syl_items);",
" ga_clear_strings(&lp->sl_comppat);",
" hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF);\n hash_init(&lp->sl_wordcount);",
" hash_clear_all(&lp->sl_map_hash, 0);",
" // Clear info from .sug file.\n slang_clear_sug(lp);",
" lp->sl_compmax = MAXWLEN;\n lp->sl_compminlen = 0;\n lp->sl_compsylmax = MAXWLEN;\n lp->sl_regions[0] = NUL;\n}",
"/*\n * Clear the info from the .sug file in \"lp\".\n */\n void\nslang_clear_sug(slang_T *lp)\n{\n VIM_CLEAR(lp->sl_sbyts);\n VIM_CLEAR(lp->sl_sidxs);\n close_spellbuf(lp->sl_sugbuf);\n lp->sl_sugbuf = NULL;\n lp->sl_sugloaded = FALSE;\n lp->sl_sugtime = 0;\n}",
"/*\n * Load one spell file and store the info into a slang_T.\n * Invoked through do_in_runtimepath().\n */\n static void\nspell_load_cb(char_u *fname, void *cookie)\n{\n spelload_T\t*slp = (spelload_T *)cookie;\n slang_T\t*slang;",
" slang = spell_load_file(fname, slp->sl_lang, NULL, FALSE);\n if (slang != NULL)\n {\n\t// When a previously loaded file has NOBREAK also use it for the\n\t// \".add\" files.\n\tif (slp->sl_nobreak && slang->sl_add)\n\t slang->sl_nobreak = TRUE;\n\telse if (slang->sl_nobreak)\n\t slp->sl_nobreak = TRUE;",
"\tslp->sl_slang = slang;\n }\n}",
"\n/*\n * Add a word to the hashtable of common words.\n * If it's already there then the counter is increased.\n */\n void\ncount_common_word(\n slang_T\t*lp,\n char_u\t*word,\n int\t\tlen,\t // word length, -1 for up to NUL\n int\t\tcount)\t // 1 to count once, 10 to init\n{\n hash_T\thash;\n hashitem_T\t*hi;\n wordcount_T\t*wc;\n char_u\tbuf[MAXWLEN];\n char_u\t*p;",
" if (len == -1)\n\tp = word;\n else if (len >= MAXWLEN)\n\treturn;\n else\n {\n\tvim_strncpy(buf, word, len);\n\tp = buf;\n }",
" hash = hash_hash(p);\n hi = hash_lookup(&lp->sl_wordcount, p, hash);\n if (HASHITEM_EMPTY(hi))\n {\n\twc = alloc(sizeof(wordcount_T) + STRLEN(p));\n\tif (wc == NULL)\n\t return;\n\tSTRCPY(wc->wc_word, p);\n\twc->wc_count = count;\n\thash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash);\n }\n else\n {\n\twc = HI2WC(hi);\n\tif ((wc->wc_count += count) < (unsigned)count)\t// check for overflow\n\t wc->wc_count = MAXWORDCOUNT;\n }\n}",
"/*\n * Return TRUE if byte \"n\" appears in \"str\".\n * Like strchr() but independent of locale.\n */\n int\nbyte_in_str(char_u *str, int n)\n{\n char_u\t*p;",
" for (p = str; *p != NUL; ++p)\n\tif (*p == n)\n\t return TRUE;\n return FALSE;\n}",
"#define SY_MAXLEN 30\ntypedef struct syl_item_S\n{\n char_u\tsy_chars[SY_MAXLEN];\t // the sequence of chars\n int\t\tsy_len;\n} syl_item_T;",
"/*\n * Truncate \"slang->sl_syllable\" at the first slash and put the following items\n * in \"slang->sl_syl_items\".\n */\n int\ninit_syl_tab(slang_T *slang)\n{\n char_u\t*p;\n char_u\t*s;\n int\t\tl;\n syl_item_T\t*syl;",
" ga_init2(&slang->sl_syl_items, sizeof(syl_item_T), 4);\n p = vim_strchr(slang->sl_syllable, '/');\n while (p != NULL)\n {\n\t*p++ = NUL;\n\tif (*p == NUL)\t // trailing slash\n\t break;\n\ts = p;\n\tp = vim_strchr(p, '/');\n\tif (p == NULL)\n\t l = (int)STRLEN(s);\n\telse\n\t l = (int)(p - s);\n\tif (l >= SY_MAXLEN)\n\t return SP_FORMERROR;\n\tif (ga_grow(&slang->sl_syl_items, 1) == FAIL)\n\t return SP_OTHERERROR;\n\tsyl = ((syl_item_T *)slang->sl_syl_items.ga_data)\n\t\t\t\t\t + slang->sl_syl_items.ga_len++;\n\tvim_strncpy(syl->sy_chars, s, l);\n\tsyl->sy_len = l;\n }\n return OK;\n}",
"/*\n * Count the number of syllables in \"word\".\n * When \"word\" contains spaces the syllables after the last space are counted.\n * Returns zero if syllables are not defines.\n */\n static int\ncount_syllables(slang_T *slang, char_u *word)\n{\n int\t\tcnt = 0;\n int\t\tskip = FALSE;\n char_u\t*p;\n int\t\tlen;\n int\t\ti;\n syl_item_T\t*syl;\n int\t\tc;",
" if (slang->sl_syllable == NULL)\n\treturn 0;",
" for (p = word; *p != NUL; p += len)\n {\n\t// When running into a space reset counter.\n\tif (*p == ' ')\n\t{\n\t len = 1;\n\t cnt = 0;\n\t continue;\n\t}",
"\t// Find longest match of syllable items.\n\tlen = 0;\n\tfor (i = 0; i < slang->sl_syl_items.ga_len; ++i)\n\t{\n\t syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i;\n\t if (syl->sy_len > len\n\t\t\t && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0)\n\t\tlen = syl->sy_len;\n\t}\n\tif (len != 0)\t// found a match, count syllable\n\t{\n\t ++cnt;\n\t skip = FALSE;\n\t}\n\telse\n\t{\n\t // No recognized syllable item, at least a syllable char then?\n\t c = mb_ptr2char(p);\n\t len = (*mb_ptr2len)(p);\n\t if (vim_strchr(slang->sl_syllable, c) == NULL)\n\t\tskip = FALSE;\t // No, search for next syllable\n\t else if (!skip)\n\t {\n\t\t++cnt;\t\t // Yes, count it\n\t\tskip = TRUE;\t // don't count following syllable chars\n\t }\n\t}\n }\n return cnt;\n}",
"/*\n * Parse 'spelllang' and set w_s->b_langp accordingly.\n * Returns NULL if it's OK, an untranslated error message otherwise.\n */\n char *\ndid_set_spelllang(win_T *wp)\n{\n garray_T\tga;\n char_u\t*splp;\n char_u\t*region;\n char_u\tregion_cp[3];\n int\t\tfilename;\n int\t\tregion_mask;\n slang_T\t*slang;\n int\t\tc;\n char_u\tlang[MAXWLEN + 1];\n char_u\tspf_name[MAXPATHL];\n int\t\tlen;\n char_u\t*p;\n int\t\tround;\n char_u\t*spf;\n char_u\t*use_region = NULL;\n int\t\tdont_use_region = FALSE;\n int\t\tnobreak = FALSE;\n int\t\ti, j;\n langp_T\t*lp, *lp2;\n static int\trecursive = FALSE;\n char\t*ret_msg = NULL;\n char_u\t*spl_copy;\n bufref_T\tbufref;",
" set_bufref(&bufref, wp->w_buffer);",
" // We don't want to do this recursively. May happen when a language is\n // not available and the SpellFileMissing autocommand opens a new buffer\n // in which 'spell' is set.\n if (recursive)\n\treturn NULL;\n recursive = TRUE;",
" ga_init2(&ga, sizeof(langp_T), 2);\n clear_midword(wp);",
" // Make a copy of 'spelllang', the SpellFileMissing autocommands may change\n // it under our fingers.\n spl_copy = vim_strsave(wp->w_s->b_p_spl);\n if (spl_copy == NULL)\n\tgoto theend;",
" wp->w_s->b_cjk = 0;",
" // Loop over comma separated language names.\n for (splp = spl_copy; *splp != NUL; )\n {\n\t// Get one language name.\n\tcopy_option_part(&splp, lang, MAXWLEN, \",\");\n\tregion = NULL;\n\tlen = (int)STRLEN(lang);",
"\tif (!valid_spelllang(lang))\n\t continue;",
"\tif (STRCMP(lang, \"cjk\") == 0)\n\t{\n\t wp->w_s->b_cjk = 1;\n\t continue;\n\t}",
"\t// If the name ends in \".spl\" use it as the name of the spell file.\n\t// If there is a region name let \"region\" point to it and remove it\n\t// from the name.\n\tif (len > 4 && fnamecmp(lang + len - 4, \".spl\") == 0)\n\t{\n\t filename = TRUE;",
"\t // Locate a region and remove it from the file name.\n\t p = vim_strchr(gettail(lang), '_');\n\t if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2])\n\t\t\t\t\t\t && !ASCII_ISALPHA(p[3]))\n\t {\n\t\tvim_strncpy(region_cp, p + 1, 2);\n\t\tmch_memmove(p, p + 3, len - (p - lang) - 2);\n\t\tregion = region_cp;\n\t }\n\t else\n\t\tdont_use_region = TRUE;",
"\t // Check if we loaded this language before.\n\t FOR_ALL_SPELL_LANGS(slang)\n\t\tif (fullpathcmp(lang, slang->sl_fname, FALSE, TRUE) == FPC_SAME)\n\t\t break;\n\t}\n\telse\n\t{\n\t filename = FALSE;\n\t if (len > 3 && lang[len - 3] == '_')\n\t {\n\t\tregion = lang + len - 2;\n\t\tlen -= 3;\n\t\tlang[len] = NUL;\n\t }\n\t else\n\t\tdont_use_region = TRUE;",
"\t // Check if we loaded this language before.\n\t FOR_ALL_SPELL_LANGS(slang)\n\t\tif (STRICMP(lang, slang->sl_name) == 0)\n\t\t break;\n\t}",
"\tif (region != NULL)\n\t{\n\t // If the region differs from what was used before then don't\n\t // use it for 'spellfile'.\n\t if (use_region != NULL && STRCMP(region, use_region) != 0)\n\t\tdont_use_region = TRUE;\n\t use_region = region;\n\t}",
"\t// If not found try loading the language now.\n\tif (slang == NULL)\n\t{\n\t if (filename)\n\t\t(void)spell_load_file(lang, lang, NULL, FALSE);\n\t else\n\t {\n\t\tspell_load_lang(lang);\n\t\t// SpellFileMissing autocommands may do anything, including\n\t\t// destroying the buffer we are using...\n\t\tif (!bufref_valid(&bufref))\n\t\t{\n\t\t ret_msg = N_(e_spellfilemising_autocommand_deleted_buffer);\n\t\t goto theend;\n\t\t}\n\t }\n\t}",
"\t/*\n\t * Loop over the languages, there can be several files for \"lang\".\n\t */\n\tFOR_ALL_SPELL_LANGS(slang)\n\t if (filename ? fullpathcmp(lang, slang->sl_fname, FALSE, TRUE)\n\t\t\t\t\t\t\t\t == FPC_SAME\n\t\t\t : STRICMP(lang, slang->sl_name) == 0)\n\t {\n\t\tregion_mask = REGION_ALL;\n\t\tif (!filename && region != NULL)\n\t\t{\n\t\t // find region in sl_regions\n\t\t c = find_region(slang->sl_regions, region);\n\t\t if (c == REGION_ALL)\n\t\t {\n\t\t\tif (slang->sl_add)\n\t\t\t{\n\t\t\t if (*slang->sl_regions != NUL)\n\t\t\t\t// This addition file is for other regions.\n\t\t\t\tregion_mask = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t // This is probably an error. Give a warning and\n\t\t\t // accept the words anyway.\n\t\t\t smsg(_(\"Warning: region %s not supported\"),\n\t\t\t\t\t\t\t\t region);\n\t\t }\n\t\t else\n\t\t\tregion_mask = 1 << c;\n\t\t}",
"\t\tif (region_mask != 0)\n\t\t{\n\t\t if (ga_grow(&ga, 1) == FAIL)\n\t\t {\n\t\t\tga_clear(&ga);\n\t\t\tret_msg = e_out_of_memory;\n\t\t\tgoto theend;\n\t\t }\n\t\t LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;\n\t\t LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;\n\t\t ++ga.ga_len;\n\t\t use_midword(slang, wp);\n\t\t if (slang->sl_nobreak)\n\t\t\tnobreak = TRUE;\n\t\t}\n\t }\n }",
" // round 0: load int_wordlist, if possible.\n // round 1: load first name in 'spellfile'.\n // round 2: load second name in 'spellfile.\n // etc.\n spf = curwin->w_s->b_p_spf;\n for (round = 0; round == 0 || *spf != NUL; ++round)\n {\n\tif (round == 0)\n\t{\n\t // Internal wordlist, if there is one.\n\t if (int_wordlist == NULL)\n\t\tcontinue;\n\t int_wordlist_spl(spf_name);\n\t}\n\telse\n\t{\n\t // One entry in 'spellfile'.\n\t copy_option_part(&spf, spf_name, MAXPATHL - 5, \",\");\n\t STRCAT(spf_name, \".spl\");",
"\t // If it was already found above then skip it.\n\t for (c = 0; c < ga.ga_len; ++c)\n\t {\n\t\tp = LANGP_ENTRY(ga, c)->lp_slang->sl_fname;\n\t\tif (p != NULL && fullpathcmp(spf_name, p, FALSE, TRUE)\n\t\t\t\t\t\t\t\t== FPC_SAME)\n\t\t break;\n\t }\n\t if (c < ga.ga_len)\n\t\tcontinue;\n\t}",
"\t// Check if it was loaded already.\n\tFOR_ALL_SPELL_LANGS(slang)\n\t if (fullpathcmp(spf_name, slang->sl_fname, FALSE, TRUE)\n\t\t\t\t\t\t\t\t== FPC_SAME)\n\t\tbreak;\n\tif (slang == NULL)\n\t{\n\t // Not loaded, try loading it now. The language name includes the\n\t // region name, the region is ignored otherwise. for int_wordlist\n\t // use an arbitrary name.\n\t if (round == 0)\n\t\tSTRCPY(lang, \"internal wordlist\");\n\t else\n\t {\n\t\tvim_strncpy(lang, gettail(spf_name), MAXWLEN);\n\t\tp = vim_strchr(lang, '.');\n\t\tif (p != NULL)\n\t\t *p = NUL;\t// truncate at \".encoding.add\"\n\t }\n\t slang = spell_load_file(spf_name, lang, NULL, TRUE);",
"\t // If one of the languages has NOBREAK we assume the addition\n\t // files also have this.\n\t if (slang != NULL && nobreak)\n\t\tslang->sl_nobreak = TRUE;\n\t}\n\tif (slang != NULL && ga_grow(&ga, 1) == OK)\n\t{\n\t region_mask = REGION_ALL;\n\t if (use_region != NULL && !dont_use_region)\n\t {\n\t\t// find region in sl_regions\n\t\tc = find_region(slang->sl_regions, use_region);\n\t\tif (c != REGION_ALL)\n\t\t region_mask = 1 << c;\n\t\telse if (*slang->sl_regions != NUL)\n\t\t // This spell file is for other regions.\n\t\t region_mask = 0;\n\t }",
"\t if (region_mask != 0)\n\t {\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_sallang = NULL;\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_replang = NULL;\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;\n\t\t++ga.ga_len;\n\t\tuse_midword(slang, wp);\n\t }\n\t}\n }",
" // Everything is fine, store the new b_langp value.\n ga_clear(&wp->w_s->b_langp);\n wp->w_s->b_langp = ga;",
" // For each language figure out what language to use for sound folding and\n // REP items. If the language doesn't support it itself use another one\n // with the same name. E.g. for \"en-math\" use \"en\".\n for (i = 0; i < ga.ga_len; ++i)\n {\n\tlp = LANGP_ENTRY(ga, i);",
"\t// sound folding\n\tif (lp->lp_slang->sl_sal.ga_len > 0)\n\t // language does sound folding itself\n\t lp->lp_sallang = lp->lp_slang;\n\telse\n\t // find first similar language that does sound folding\n\t for (j = 0; j < ga.ga_len; ++j)\n\t {\n\t\tlp2 = LANGP_ENTRY(ga, j);\n\t\tif (lp2->lp_slang->sl_sal.ga_len > 0\n\t\t\t&& STRNCMP(lp->lp_slang->sl_name,\n\t\t\t\t\t lp2->lp_slang->sl_name, 2) == 0)\n\t\t{\n\t\t lp->lp_sallang = lp2->lp_slang;\n\t\t break;\n\t\t}\n\t }",
"\t// REP items\n\tif (lp->lp_slang->sl_rep.ga_len > 0)\n\t // language has REP items itself\n\t lp->lp_replang = lp->lp_slang;\n\telse\n\t // find first similar language that has REP items\n\t for (j = 0; j < ga.ga_len; ++j)\n\t {\n\t\tlp2 = LANGP_ENTRY(ga, j);\n\t\tif (lp2->lp_slang->sl_rep.ga_len > 0\n\t\t\t&& STRNCMP(lp->lp_slang->sl_name,\n\t\t\t\t\t lp2->lp_slang->sl_name, 2) == 0)\n\t\t{\n\t\t lp->lp_replang = lp2->lp_slang;\n\t\t break;\n\t\t}\n\t }\n }\n redraw_win_later(wp, NOT_VALID);",
"theend:\n vim_free(spl_copy);\n recursive = FALSE;\n return ret_msg;\n}",
"/*\n * Clear the midword characters for buffer \"buf\".\n */\n static void\nclear_midword(win_T *wp)\n{\n CLEAR_FIELD(wp->w_s->b_spell_ismw);\n VIM_CLEAR(wp->w_s->b_spell_ismw_mb);\n}",
"/*\n * Use the \"sl_midword\" field of language \"lp\" for buffer \"buf\".\n * They add up to any currently used midword characters.\n */\n static void\nuse_midword(slang_T *lp, win_T *wp)\n{\n char_u\t*p;",
" if (lp->sl_midword == NULL)\t // there aren't any\n\treturn;",
" for (p = lp->sl_midword; *p != NUL; )\n\tif (has_mbyte)\n\t{\n\t int\t c, l, n;\n\t char_u *bp;",
"\t c = mb_ptr2char(p);\n\t l = (*mb_ptr2len)(p);\n\t if (c < 256 && l <= 2)\n\t\twp->w_s->b_spell_ismw[c] = TRUE;\n\t else if (wp->w_s->b_spell_ismw_mb == NULL)\n\t\t// First multi-byte char in \"b_spell_ismw_mb\".\n\t\twp->w_s->b_spell_ismw_mb = vim_strnsave(p, l);\n\t else\n\t {\n\t\t// Append multi-byte chars to \"b_spell_ismw_mb\".\n\t\tn = (int)STRLEN(wp->w_s->b_spell_ismw_mb);\n\t\tbp = vim_strnsave(wp->w_s->b_spell_ismw_mb, n + l);\n\t\tif (bp != NULL)\n\t\t{\n\t\t vim_free(wp->w_s->b_spell_ismw_mb);\n\t\t wp->w_s->b_spell_ismw_mb = bp;\n\t\t vim_strncpy(bp + n, p, l);\n\t\t}\n\t }\n\t p += l;\n\t}\n\telse\n\t wp->w_s->b_spell_ismw[*p++] = TRUE;\n}",
"/*\n * Find the region \"region[2]\" in \"rp\" (points to \"sl_regions\").\n * Each region is simply stored as the two characters of its name.\n * Returns the index if found (first is 0), REGION_ALL if not found.\n */\n static int\nfind_region(char_u *rp, char_u *region)\n{\n int\t\ti;",
" for (i = 0; ; i += 2)\n {\n\tif (rp[i] == NUL)\n\t return REGION_ALL;\n\tif (rp[i] == region[0] && rp[i + 1] == region[1])\n\t break;\n }\n return i / 2;\n}",
"/*\n * Return case type of word:\n * w word\t0\n * Word\t\tWF_ONECAP\n * W WORD\tWF_ALLCAP\n * WoRd\twOrd\tWF_KEEPCAP\n */\n int\ncaptype(\n char_u\t*word,\n char_u\t*end)\t // When NULL use up to NUL byte.\n{\n char_u\t*p;\n int\t\tc;\n int\t\tfirstcap;\n int\t\tallcap;\n int\t\tpast_second = FALSE;\t// past second word char",
" // find first letter\n for (p = word; !spell_iswordp_nmw(p, curwin); MB_PTR_ADV(p))\n\tif (end == NULL ? *p == NUL : p >= end)\n\t return 0;\t // only non-word characters, illegal word\n if (has_mbyte)\n\tc = mb_ptr2char_adv(&p);\n else\n\tc = *p++;\n firstcap = allcap = SPELL_ISUPPER(c);",
" /*\n * Need to check all letters to find a word with mixed upper/lower.\n * But a word with an upper char only at start is a ONECAP.\n */\n for ( ; end == NULL ? *p != NUL : p < end; MB_PTR_ADV(p))\n\tif (spell_iswordp_nmw(p, curwin))\n\t{\n\t c = PTR2CHAR(p);\n\t if (!SPELL_ISUPPER(c))\n\t {\n\t\t// UUl -> KEEPCAP\n\t\tif (past_second && allcap)\n\t\t return WF_KEEPCAP;\n\t\tallcap = FALSE;\n\t }\n\t else if (!allcap)\n\t\t// UlU -> KEEPCAP\n\t\treturn WF_KEEPCAP;\n\t past_second = TRUE;\n\t}",
" if (allcap)\n\treturn WF_ALLCAP;\n if (firstcap)\n\treturn WF_ONECAP;\n return 0;\n}",
"/*\n * Delete the internal wordlist and its .spl file.\n */\n void\nspell_delete_wordlist(void)\n{\n char_u\tfname[MAXPATHL];",
" if (int_wordlist != NULL)\n {\n\tmch_remove(int_wordlist);\n\tint_wordlist_spl(fname);\n\tmch_remove(fname);\n\tVIM_CLEAR(int_wordlist);\n }\n}",
"/*\n * Free all languages.\n */\n void\nspell_free_all(void)\n{\n slang_T\t*slang;\n buf_T\t*buf;",
" // Go through all buffers and handle 'spelllang'. <VN>\n FOR_ALL_BUFFERS(buf)\n\tga_clear(&buf->b_s.b_langp);",
" while (first_lang != NULL)\n {\n\tslang = first_lang;\n\tfirst_lang = slang->sl_next;\n\tslang_free(slang);\n }",
" spell_delete_wordlist();",
" VIM_CLEAR(repl_to);\n VIM_CLEAR(repl_from);\n}",
"/*\n * Clear all spelling tables and reload them.\n * Used after 'encoding' is set and when \":mkspell\" was used.\n */\n void\nspell_reload(void)\n{\n win_T\t*wp;",
" // Initialize the table for spell_iswordp().\n init_spell_chartab();",
" // Unload all allocated memory.\n spell_free_all();",
" // Go through all buffers and handle 'spelllang'.\n FOR_ALL_WINDOWS(wp)\n {\n\t// Only load the wordlists when 'spelllang' is set and there is a\n\t// window for this buffer in which 'spell' is set.\n\tif (*wp->w_s->b_p_spl != NUL)\n\t{\n\t\tif (wp->w_p_spell)\n\t\t{\n\t\t (void)did_set_spelllang(wp);\n\t\t break;\n\t\t}\n\t}\n }\n}",
"/*\n * Open a spell buffer. This is a nameless buffer that is not in the buffer\n * list and only contains text lines. Can use a swapfile to reduce memory\n * use.\n * Most other fields are invalid! Esp. watch out for string options being\n * NULL and there is no undo info.\n * Returns NULL when out of memory.\n */\n buf_T *\nopen_spellbuf(void)\n{\n buf_T\t*buf;",
" buf = ALLOC_CLEAR_ONE(buf_T);\n if (buf != NULL)\n {\n\tbuf->b_spell = TRUE;\n\tbuf->b_p_swf = TRUE;\t// may create a swap file\n#ifdef FEAT_CRYPT\n\tbuf->b_p_key = empty_option;\n#endif\n\tml_open(buf);\n\tml_open_file(buf);\t// create swap file now\n }\n return buf;\n}",
"/*\n * Close the buffer used for spell info.\n */\n void\nclose_spellbuf(buf_T *buf)\n{\n if (buf != NULL)\n {\n\tml_close(buf, TRUE);\n\tvim_free(buf);\n }\n}",
"/*\n * Init the chartab used for spelling for ASCII.\n */\n void\nclear_spell_chartab(spelltab_T *sp)\n{\n int\t\ti;",
" // Init everything to FALSE (zero).\n CLEAR_FIELD(sp->st_isw);\n CLEAR_FIELD(sp->st_isu);\n for (i = 0; i < 256; ++i)\n {\n\tsp->st_fold[i] = i;\n\tsp->st_upper[i] = i;\n }",
" // We include digits. A word shouldn't start with a digit, but handling\n // that is done separately.\n for (i = '0'; i <= '9'; ++i)\n\tsp->st_isw[i] = TRUE;\n for (i = 'A'; i <= 'Z'; ++i)\n {\n\tsp->st_isw[i] = TRUE;\n\tsp->st_isu[i] = TRUE;\n\tsp->st_fold[i] = i + 0x20;\n }\n for (i = 'a'; i <= 'z'; ++i)\n {\n\tsp->st_isw[i] = TRUE;\n\tsp->st_upper[i] = i - 0x20;\n }\n}",
"/*\n * Init the chartab used for spelling. Only depends on 'encoding'.\n * Called once while starting up and when 'encoding' changes.\n * The default is to use isalpha(), but the spell file should define the word\n * characters to make it possible that 'encoding' differs from the current\n * locale. For utf-8 we don't use isalpha() but our own functions.\n */\n void\ninit_spell_chartab(void)\n{\n int\t i;",
" did_set_spelltab = FALSE;\n clear_spell_chartab(&spelltab);\n if (enc_dbcs)\n {\n\t// DBCS: assume double-wide characters are word characters.\n\tfor (i = 128; i <= 255; ++i)\n\t if (MB_BYTE2LEN(i) == 2)\n\t\tspelltab.st_isw[i] = TRUE;\n }\n else if (enc_utf8)\n {\n\tfor (i = 128; i < 256; ++i)\n\t{\n\t int f = utf_fold(i);\n\t int u = utf_toupper(i);",
"\t spelltab.st_isu[i] = utf_isupper(i);\n\t spelltab.st_isw[i] = spelltab.st_isu[i] || utf_islower(i);\n\t // The folded/upper-cased value is different between latin1 and\n\t // utf8 for 0xb5, causing E763 for no good reason. Use the latin1\n\t // value for utf-8 to avoid this.\n\t spelltab.st_fold[i] = (f < 256) ? f : i;\n\t spelltab.st_upper[i] = (u < 256) ? u : i;\n\t}\n }\n else\n {\n\t// Rough guess: use locale-dependent library functions.\n\tfor (i = 128; i < 256; ++i)\n\t{\n\t if (MB_ISUPPER(i))\n\t {\n\t\tspelltab.st_isw[i] = TRUE;\n\t\tspelltab.st_isu[i] = TRUE;\n\t\tspelltab.st_fold[i] = MB_TOLOWER(i);\n\t }\n\t else if (MB_ISLOWER(i))\n\t {\n\t\tspelltab.st_isw[i] = TRUE;\n\t\tspelltab.st_upper[i] = MB_TOUPPER(i);\n\t }\n\t}\n }\n}",
"\n/*\n * Return TRUE if \"p\" points to a word character.\n * As a special case we see \"midword\" characters as word character when it is\n * followed by a word character. This finds they'there but not 'they there'.\n * Thus this only works properly when past the first character of the word.\n */\n int\nspell_iswordp(\n char_u\t*p,\n win_T\t*wp)\t // buffer used\n{\n char_u\t*s;\n int\t\tl;\n int\t\tc;",
" if (has_mbyte)\n {\n\tl = mb_ptr2len(p);\n\ts = p;\n\tif (l == 1)\n\t{\n\t // be quick for ASCII\n\t if (wp->w_s->b_spell_ismw[*p])\n\t\ts = p + 1;\t\t// skip a mid-word character\n\t}\n\telse\n\t{\n\t c = mb_ptr2char(p);\n\t if (c < 256 ? wp->w_s->b_spell_ismw[c]\n\t\t : (wp->w_s->b_spell_ismw_mb != NULL\n\t\t\t && vim_strchr(wp->w_s->b_spell_ismw_mb, c) != NULL))\n\t\ts = p + l;\n\t}",
"\tc = mb_ptr2char(s);\n\tif (c > 255)\n\t return spell_mb_isword_class(mb_get_class(s), wp);\n\treturn spelltab.st_isw[c];\n }",
" return spelltab.st_isw[wp->w_s->b_spell_ismw[*p] ? p[1] : p[0]];\n}",
"/*\n * Return TRUE if \"p\" points to a word character.\n * Unlike spell_iswordp() this doesn't check for \"midword\" characters.\n */\n int\nspell_iswordp_nmw(char_u *p, win_T *wp)\n{\n int\t\tc;",
" if (has_mbyte)\n {\n\tc = mb_ptr2char(p);\n\tif (c > 255)\n\t return spell_mb_isword_class(mb_get_class(p), wp);\n\treturn spelltab.st_isw[c];\n }\n return spelltab.st_isw[*p];\n}",
"/*\n * Return TRUE if word class indicates a word character.\n * Only for characters above 255.\n * Unicode subscript and superscript are not considered word characters.\n * See also dbcs_class() and utf_class() in mbyte.c.\n */\n static int\nspell_mb_isword_class(int cl, win_T *wp)\n{\n if (wp->w_s->b_cjk)\n\t// East Asian characters are not considered word characters.\n\treturn cl == 2 || cl == 0x2800;\n return cl >= 2 && cl != 0x2070 && cl != 0x2080 && cl != 3;\n}",
"/*\n * Return TRUE if \"p\" points to a word character.\n * Wide version of spell_iswordp().\n */\n static int\nspell_iswordp_w(int *p, win_T *wp)\n{\n int\t\t*s;",
" if (*p < 256 ? wp->w_s->b_spell_ismw[*p]\n\t\t : (wp->w_s->b_spell_ismw_mb != NULL\n\t\t\t && vim_strchr(wp->w_s->b_spell_ismw_mb, *p) != NULL))\n\ts = p + 1;\n else\n\ts = p;",
" if (*s > 255)\n {\n\tif (enc_utf8)\n\t return spell_mb_isword_class(utf_class(*s), wp);\n\tif (enc_dbcs)\n\t return spell_mb_isword_class(\n\t\t\t\tdbcs_class((unsigned)*s >> 8, *s & 0xff), wp);\n\treturn 0;\n }\n return spelltab.st_isw[*s];\n}",
"/*\n * Case-fold \"str[len]\" into \"buf[buflen]\". The result is NUL terminated.\n * Uses the character definitions from the .spl file.\n * When using a multi-byte 'encoding' the length may change!\n * Returns FAIL when something wrong.\n */\n int\nspell_casefold(\n win_T\t*wp,\n char_u\t*str,\n int\t\tlen,\n char_u\t*buf,\n int\t\tbuflen)\n{\n int\t\ti;",
" if (len >= buflen)\n {\n\tbuf[0] = NUL;\n\treturn FAIL;\t\t// result will not fit\n }",
" if (has_mbyte)\n {\n\tint\touti = 0;\n\tchar_u\t*p;\n\tint\tc;",
"\t// Fold one character at a time.\n\tfor (p = str; p < str + len; )\n\t{\n\t if (outi + MB_MAXBYTES > buflen)\n\t {\n\t\tbuf[outi] = NUL;\n\t\treturn FAIL;\n\t }\n\t c = mb_cptr2char_adv(&p);",
"\t // Exception: greek capital sigma 0x03A3 folds to 0x03C3, except\n\t // when it is the last character in a word, then it folds to\n\t // 0x03C2.\n\t if (c == 0x03a3 || c == 0x03c2)\n\t {\n\t\tif (p == str + len || !spell_iswordp(p, wp))\n\t\t c = 0x03c2;\n\t\telse\n\t\t c = 0x03c3;\n\t }\n\t else\n\t\tc = SPELL_TOFOLD(c);",
"\t outi += mb_char2bytes(c, buf + outi);\n\t}\n\tbuf[outi] = NUL;\n }\n else\n {\n\t// Be quick for non-multibyte encodings.\n\tfor (i = 0; i < len; ++i)\n\t buf[i] = spelltab.st_fold[str[i]];\n\tbuf[i] = NUL;\n }",
" return OK;\n}",
"/*\n * Check if the word at line \"lnum\" column \"col\" is required to start with a\n * capital. This uses 'spellcapcheck' of the current buffer.\n */\n int\ncheck_need_cap(linenr_T lnum, colnr_T col)\n{\n int\t\tneed_cap = FALSE;\n char_u\t*line;\n char_u\t*line_copy = NULL;\n char_u\t*p;\n colnr_T\tendcol;\n regmatch_T\tregmatch;",
" if (curwin->w_s->b_cap_prog == NULL)\n\treturn FALSE;",
" line = ml_get_curline();\n endcol = 0;\n if (getwhitecols(line) >= (int)col)\n {\n\t// At start of line, check if previous line is empty or sentence\n\t// ends there.\n\tif (lnum == 1)\n\t need_cap = TRUE;\n\telse\n\t{\n\t line = ml_get(lnum - 1);\n\t if (*skipwhite(line) == NUL)\n\t\tneed_cap = TRUE;\n\t else\n\t {\n\t\t// Append a space in place of the line break.\n\t\tline_copy = concat_str(line, (char_u *)\" \");\n\t\tline = line_copy;\n\t\tendcol = (colnr_T)STRLEN(line);\n\t }\n\t}\n }\n else\n\tendcol = col;",
" if (endcol > 0)\n {\n\t// Check if sentence ends before the bad word.\n\tregmatch.regprog = curwin->w_s->b_cap_prog;\n\tregmatch.rm_ic = FALSE;\n\tp = line + endcol;\n\tfor (;;)\n\t{\n\t MB_PTR_BACK(line, p);\n\t if (p == line || spell_iswordp_nmw(p, curwin))\n\t\tbreak;\n\t if (vim_regexec(®match, p, 0)\n\t\t\t\t\t && regmatch.endp[0] == line + endcol)\n\t {\n\t\tneed_cap = TRUE;\n\t\tbreak;\n\t }\n\t}\n\tcurwin->w_s->b_cap_prog = regmatch.regprog;\n }",
" vim_free(line_copy);",
" return need_cap;\n}",
"\n/*\n * \":spellrepall\"\n */\n void\nex_spellrepall(exarg_T *eap UNUSED)\n{\n pos_T\tpos = curwin->w_cursor;\n char_u\t*frompat;\n int\t\taddlen;\n char_u\t*line;\n char_u\t*p;\n int\t\tsave_ws = p_ws;\n linenr_T\tprev_lnum = 0;",
" if (repl_from == NULL || repl_to == NULL)\n {\n\temsg(_(e_no_previous_spell_replacement));\n\treturn;\n }\n addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from));",
" frompat = alloc(STRLEN(repl_from) + 7);\n if (frompat == NULL)\n\treturn;\n sprintf((char *)frompat, \"\\\\V\\\\<%s\\\\>\", repl_from);\n p_ws = FALSE;",
" sub_nsubs = 0;\n sub_nlines = 0;\n curwin->w_cursor.lnum = 0;\n while (!got_int)\n {\n\tif (do_search(NULL, '/', '/', frompat, 1L, SEARCH_KEEP, NULL) == 0\n\t\t\t\t\t\t || u_save_cursor() == FAIL)\n\t break;",
"\t// Only replace when the right word isn't there yet. This happens\n\t// when changing \"etc\" to \"etc.\".\n\tline = ml_get_curline();\n\tif (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col,\n\t\t\t\t\t repl_to, STRLEN(repl_to)) != 0)\n\t{\n\t p = alloc(STRLEN(line) + addlen + 1);\n\t if (p == NULL)\n\t\tbreak;\n\t mch_memmove(p, line, curwin->w_cursor.col);\n\t STRCPY(p + curwin->w_cursor.col, repl_to);\n\t STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from));\n\t ml_replace(curwin->w_cursor.lnum, p, FALSE);\n\t changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);\n\t if (curbuf->b_has_textprop && addlen != 0)\n\t\tadjust_prop_columns(curwin->w_cursor.lnum,\n\t\t\t\t curwin->w_cursor.col, addlen, APC_SUBSTITUTE);",
"\t if (curwin->w_cursor.lnum != prev_lnum)\n\t {\n\t\t++sub_nlines;\n\t\tprev_lnum = curwin->w_cursor.lnum;\n\t }\n\t ++sub_nsubs;\n\t}\n\tcurwin->w_cursor.col += (colnr_T)STRLEN(repl_to);\n }",
" p_ws = save_ws;\n curwin->w_cursor = pos;\n vim_free(frompat);",
" if (sub_nsubs == 0)\n\tsemsg(_(e_not_found_str), repl_from);\n else\n\tdo_sub_msg(FALSE);\n}",
"/*\n * Make a copy of \"word\", with the first letter upper or lower cased, to\n * \"wcopy[MAXWLEN]\". \"word\" must not be empty.\n * The result is NUL terminated.\n */\n void\nonecap_copy(\n char_u\t*word,\n char_u\t*wcopy,\n int\t\tupper)\t // TRUE: first letter made upper case\n{\n char_u\t*p;\n int\t\tc;\n int\t\tl;",
" p = word;\n if (has_mbyte)\n\tc = mb_cptr2char_adv(&p);\n else\n\tc = *p++;\n if (upper)\n\tc = SPELL_TOUPPER(c);\n else\n\tc = SPELL_TOFOLD(c);\n if (has_mbyte)\n\tl = mb_char2bytes(c, wcopy);\n else\n {\n\tl = 1;\n\twcopy[0] = c;\n }\n vim_strncpy(wcopy + l, p, MAXWLEN - l - 1);\n}",
"/*\n * Make a copy of \"word\" with all the letters upper cased into\n * \"wcopy[MAXWLEN]\". The result is NUL terminated.\n */\n void\nallcap_copy(char_u *word, char_u *wcopy)\n{\n char_u\t*s;\n char_u\t*d;\n int\t\tc;",
" d = wcopy;\n for (s = word; *s != NUL; )\n {\n\tif (has_mbyte)\n\t c = mb_cptr2char_adv(&s);\n\telse\n\t c = *s++;",
"\t// We only change 0xdf to SS when we are certain latin1 is used. It\n\t// would cause weird errors in other 8-bit encodings.\n\tif (enc_latin1like && c == 0xdf)\n\t{\n\t c = 'S';\n\t if (d - wcopy >= MAXWLEN - 1)\n\t\tbreak;\n\t *d++ = c;\n\t}\n\telse\n\t c = SPELL_TOUPPER(c);",
"\tif (has_mbyte)\n\t{\n\t if (d - wcopy >= MAXWLEN - MB_MAXBYTES)\n\t\tbreak;\n\t d += mb_char2bytes(c, d);\n\t}\n\telse\n\t{\n\t if (d - wcopy >= MAXWLEN - 1)\n\t\tbreak;\n\t *d++ = c;\n\t}\n }\n *d = NUL;\n}",
"/*\n * Case-folding may change the number of bytes: Count nr of chars in\n * fword[flen] and return the byte length of that many chars in \"word\".\n */\n int\nnofold_len(char_u *fword, int flen, char_u *word)\n{\n char_u\t*p;\n int\t\ti = 0;",
" for (p = fword; p < fword + flen; MB_PTR_ADV(p))\n\t++i;\n for (p = word; i > 0; MB_PTR_ADV(p))\n\t--i;\n return (int)(p - word);\n}",
"/*\n * Copy \"fword\" to \"cword\", fixing case according to \"flags\".\n */\n void\nmake_case_word(char_u *fword, char_u *cword, int flags)\n{\n if (flags & WF_ALLCAP)\n\t// Make it all upper-case\n\tallcap_copy(fword, cword);\n else if (flags & WF_ONECAP)\n\t// Make the first letter upper-case\n\tonecap_copy(fword, cword, TRUE);\n else\n\t// Use goodword as-is.\n\tSTRCPY(cword, fword);\n}",
"#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Soundfold a string, for soundfold().\n * Result is in allocated memory, NULL for an error.\n */\n char_u *\neval_soundfold(char_u *word)\n{\n langp_T\t*lp;\n char_u\tsound[MAXWLEN];\n int\t\tlpi;",
" if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)\n\t// Use the sound-folding of the first language that supports it.\n\tfor (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)\n\t{\n\t lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\t if (lp->lp_slang->sl_sal.ga_len > 0)\n\t {\n\t\t// soundfold the word\n\t\tspell_soundfold(lp->lp_slang, word, FALSE, sound);\n\t\treturn vim_strsave(sound);\n\t }\n\t}",
" // No language with sound folding, return word as-is.\n return vim_strsave(word);\n}\n#endif",
"/*\n * Turn \"inword\" into its sound-a-like equivalent in \"res[MAXWLEN]\".\n *\n * There are many ways to turn a word into a sound-a-like representation. The\n * oldest is Soundex (1918!). A nice overview can be found in \"Approximate\n * swedish name matching - survey and test of different algorithms\" by Klas\n * Erikson.\n *\n * We support two methods:\n * 1. SOFOFROM/SOFOTO do a simple character mapping.\n * 2. SAL items define a more advanced sound-folding (and much slower).\n */\n void\nspell_soundfold(\n slang_T\t*slang,\n char_u\t*inword,\n int\t\tfolded,\t // \"inword\" is already case-folded\n char_u\t*res)\n{\n char_u\tfword[MAXWLEN];\n char_u\t*word;",
" if (slang->sl_sofo)\n\t// SOFOFROM and SOFOTO used\n\tspell_soundfold_sofo(slang, inword, res);\n else\n {\n\t// SAL items used. Requires the word to be case-folded.\n\tif (folded)\n\t word = inword;\n\telse\n\t{\n\t (void)spell_casefold(curwin,\n\t\t\t\t inword, (int)STRLEN(inword), fword, MAXWLEN);\n\t word = fword;\n\t}",
"\tif (has_mbyte)\n\t spell_soundfold_wsal(slang, word, res);\n\telse\n\t spell_soundfold_sal(slang, word, res);\n }\n}",
"/*\n * Perform sound folding of \"inword\" into \"res\" according to SOFOFROM and\n * SOFOTO lines.\n */\n static void\nspell_soundfold_sofo(slang_T *slang, char_u *inword, char_u *res)\n{\n char_u\t*s;\n int\t\tri = 0;\n int\t\tc;",
" if (has_mbyte)\n {\n\tint\tprevc = 0;\n\tint\t*ip;",
"\t// The sl_sal_first[] table contains the translation for chars up to\n\t// 255, sl_sal the rest.\n\tfor (s = inword; *s != NUL; )\n\t{\n\t c = mb_cptr2char_adv(&s);\n\t if (enc_utf8 ? utf_class(c) == 0 : VIM_ISWHITE(c))\n\t\tc = ' ';\n\t else if (c < 256)\n\t\tc = slang->sl_sal_first[c];\n\t else\n\t {\n\t\tip = ((int **)slang->sl_sal.ga_data)[c & 0xff];\n\t\tif (ip == NULL)\t\t// empty list, can't match\n\t\t c = NUL;\n\t\telse\n\t\t for (;;)\t\t// find \"c\" in the list\n\t\t {\n\t\t\tif (*ip == 0)\t// not found\n\t\t\t{\n\t\t\t c = NUL;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (*ip == c)\t// match!\n\t\t\t{\n\t\t\t c = ip[1];\n\t\t\t break;\n\t\t\t}\n\t\t\tip += 2;\n\t\t }\n\t }",
"\t if (c != NUL && c != prevc)\n\t {\n\t\tri += mb_char2bytes(c, res + ri);\n\t\tif (ri + MB_MAXBYTES > MAXWLEN)\n\t\t break;\n\t\tprevc = c;\n\t }\n\t}\n }\n else\n {\n\t// The sl_sal_first[] table contains the translation.\n\tfor (s = inword; (c = *s) != NUL; ++s)\n\t{\n\t if (VIM_ISWHITE(c))\n\t\tc = ' ';\n\t else\n\t\tc = slang->sl_sal_first[c];\n\t if (c != NUL && (ri == 0 || res[ri - 1] != c))\n\t\tres[ri++] = c;\n\t}\n }",
" res[ri] = NUL;\n}",
" static void\nspell_soundfold_sal(slang_T *slang, char_u *inword, char_u *res)\n{\n salitem_T\t*smp;\n char_u\tword[MAXWLEN];\n char_u\t*s = inword;\n char_u\t*t;\n char_u\t*pf;\n int\t\ti, j, z;\n int\t\treslen;\n int\t\tn, k = 0;\n int\t\tz0;\n int\t\tk0;\n int\t\tn0;\n int\t\tc;\n int\t\tpri;\n int\t\tp0 = -333;\n int\t\tc0;",
" // Remove accents, if wanted. We actually remove all non-word characters.\n // But keep white space. We need a copy, the word may be changed here.\n if (slang->sl_rem_accents)\n {\n\tt = word;\n\twhile (*s != NUL)\n\t{\n\t if (VIM_ISWHITE(*s))\n\t {\n\t\t*t++ = ' ';\n\t\ts = skipwhite(s);\n\t }\n\t else\n\t {\n\t\tif (spell_iswordp_nmw(s, curwin))\n\t\t *t++ = *s;\n\t\t++s;\n\t }\n\t}\n\t*t = NUL;\n }\n else\n\tvim_strncpy(word, s, MAXWLEN - 1);",
" smp = (salitem_T *)slang->sl_sal.ga_data;",
" /*\n * This comes from Aspell phonet.cpp. Converted from C++ to C.\n * Changed to keep spaces.\n */\n i = reslen = z = 0;\n while ((c = word[i]) != NUL)\n {\n\t// Start with the first rule that has the character in the word.\n\tn = slang->sl_sal_first[c];\n\tz0 = 0;",
"\tif (n >= 0)\n\t{\n\t // check all rules for the same letter\n\t for (; (s = smp[n].sm_lead)[0] == c; ++n)\n\t {\n\t\t// Quickly skip entries that don't match the word. Most\n\t\t// entries are less than three chars, optimize for that.\n\t\tk = smp[n].sm_leadlen;\n\t\tif (k > 1)\n\t\t{\n\t\t if (word[i + 1] != s[1])\n\t\t\tcontinue;\n\t\t if (k > 2)\n\t\t {\n\t\t\tfor (j = 2; j < k; ++j)\n\t\t\t if (word[i + j] != s[j])\n\t\t\t\tbreak;\n\t\t\tif (j < k)\n\t\t\t continue;\n\t\t }\n\t\t}",
"\t\tif ((pf = smp[n].sm_oneof) != NULL)\n\t\t{\n\t\t // Check for match with one of the chars in \"sm_oneof\".\n\t\t while (*pf != NUL && *pf != word[i + k])\n\t\t\t++pf;\n\t\t if (*pf == NUL)\n\t\t\tcontinue;\n\t\t ++k;\n\t\t}\n\t\ts = smp[n].sm_rules;\n\t\tpri = 5; // default priority",
"\t\tp0 = *s;\n\t\tk0 = k;\n\t\twhile (*s == '-' && k > 1)\n\t\t{\n\t\t k--;\n\t\t s++;\n\t\t}\n\t\tif (*s == '<')\n\t\t s++;\n\t\tif (VIM_ISDIGIT(*s))\n\t\t{\n\t\t // determine priority\n\t\t pri = *s - '0';\n\t\t s++;\n\t\t}\n\t\tif (*s == '^' && *(s + 1) == '^')\n\t\t s++;",
"\t\tif (*s == NUL\n\t\t\t|| (*s == '^'\n\t\t\t && (i == 0 || !(word[i - 1] == ' '\n\t\t\t\t || spell_iswordp(word + i - 1, curwin)))\n\t\t\t && (*(s + 1) != '$'\n\t\t\t\t|| (!spell_iswordp(word + i + k0, curwin))))\n\t\t\t|| (*s == '$' && i > 0\n\t\t\t && spell_iswordp(word + i - 1, curwin)\n\t\t\t && (!spell_iswordp(word + i + k0, curwin))))\n\t\t{\n\t\t // search for followup rules, if:\n\t\t // followup and k > 1 and NO '-' in searchstring\n\t\t c0 = word[i + k - 1];\n\t\t n0 = slang->sl_sal_first[c0];",
"\t\t if (slang->sl_followup && k > 1 && n0 >= 0\n\t\t\t\t\t && p0 != '-' && word[i + k] != NUL)\n\t\t {\n\t\t\t// test follow-up rule for \"word[i + k]\"\n\t\t\tfor ( ; (s = smp[n0].sm_lead)[0] == c0; ++n0)\n\t\t\t{\n\t\t\t // Quickly skip entries that don't match the word.\n\t\t\t //\n\t\t\t k0 = smp[n0].sm_leadlen;\n\t\t\t if (k0 > 1)\n\t\t\t {\n\t\t\t\tif (word[i + k] != s[1])\n\t\t\t\t continue;\n\t\t\t\tif (k0 > 2)\n\t\t\t\t{\n\t\t\t\t pf = word + i + k + 1;\n\t\t\t\t for (j = 2; j < k0; ++j)\n\t\t\t\t\tif (*pf++ != s[j])\n\t\t\t\t\t break;\n\t\t\t\t if (j < k0)\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t }\n\t\t\t k0 += k - 1;",
"\t\t\t if ((pf = smp[n0].sm_oneof) != NULL)\n\t\t\t {\n\t\t\t\t// Check for match with one of the chars in\n\t\t\t\t// \"sm_oneof\".\n\t\t\t\twhile (*pf != NUL && *pf != word[i + k0])\n\t\t\t\t ++pf;\n\t\t\t\tif (*pf == NUL)\n\t\t\t\t continue;\n\t\t\t\t++k0;\n\t\t\t }",
"\t\t\t p0 = 5;\n\t\t\t s = smp[n0].sm_rules;\n\t\t\t while (*s == '-')\n\t\t\t {\n\t\t\t\t// \"k0\" gets NOT reduced because\n\t\t\t\t// \"if (k0 == k)\"\n\t\t\t\ts++;\n\t\t\t }\n\t\t\t if (*s == '<')\n\t\t\t\ts++;\n\t\t\t if (VIM_ISDIGIT(*s))\n\t\t\t {\n\t\t\t\tp0 = *s - '0';\n\t\t\t\ts++;\n\t\t\t }",
"\t\t\t if (*s == NUL\n\t\t\t\t // *s == '^' cuts\n\t\t\t\t || (*s == '$'\n\t\t\t\t\t && !spell_iswordp(word + i + k0,\n\t\t\t\t\t\t\t\t curwin)))\n\t\t\t {\n\t\t\t\tif (k0 == k)\n\t\t\t\t // this is just a piece of the string\n\t\t\t\t continue;",
"\t\t\t\tif (p0 < pri)\n\t\t\t\t // priority too low\n\t\t\t\t continue;\n\t\t\t\t// rule fits; stop search\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}",
"\t\t\tif (p0 >= pri && smp[n0].sm_lead[0] == c0)\n\t\t\t continue;\n\t\t }",
"\t\t // replace string\n\t\t s = smp[n].sm_to;\n\t\t if (s == NULL)\n\t\t\ts = (char_u *)\"\";\n\t\t pf = smp[n].sm_rules;\n\t\t p0 = (vim_strchr(pf, '<') != NULL) ? 1 : 0;\n\t\t if (p0 == 1 && z == 0)\n\t\t {\n\t\t\t// rule with '<' is used\n\t\t\tif (reslen > 0 && *s != NUL && (res[reslen - 1] == c\n\t\t\t\t\t\t || res[reslen - 1] == *s))\n\t\t\t reslen--;\n\t\t\tz0 = 1;\n\t\t\tz = 1;\n\t\t\tk0 = 0;\n\t\t\twhile (*s != NUL && word[i + k0] != NUL)\n\t\t\t{\n\t\t\t word[i + k0] = *s;\n\t\t\t k0++;\n\t\t\t s++;\n\t\t\t}\n\t\t\tif (k > k0)\n\t\t\t STRMOVE(word + i + k0, word + i + k);",
"\t\t\t// new \"actual letter\"\n\t\t\tc = word[i];\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// no '<' rule used\n\t\t\ti += k - 1;\n\t\t\tz = 0;\n\t\t\twhile (*s != NUL && s[1] != NUL && reslen < MAXWLEN)\n\t\t\t{\n\t\t\t if (reslen == 0 || res[reslen - 1] != *s)\n\t\t\t\tres[reslen++] = *s;\n\t\t\t s++;\n\t\t\t}\n\t\t\t// new \"actual letter\"\n\t\t\tc = *s;\n\t\t\tif (strstr((char *)pf, \"^^\") != NULL)\n\t\t\t{\n\t\t\t if (c != NUL)\n\t\t\t\tres[reslen++] = c;\n\t\t\t STRMOVE(word, word + i + 1);\n\t\t\t i = 0;\n\t\t\t z0 = 1;\n\t\t\t}\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\t}\n\telse if (VIM_ISWHITE(c))\n\t{\n\t c = ' ';\n\t k = 1;\n\t}",
"\tif (z0 == 0)\n\t{\n\t if (k && !p0 && reslen < MAXWLEN && c != NUL\n\t\t && (!slang->sl_collapse || reslen == 0\n\t\t\t\t\t\t || res[reslen - 1] != c))\n\t\t// condense only double letters\n\t\tres[reslen++] = c;",
"\t i++;\n\t z = 0;\n\t k = 0;\n\t}\n }",
" res[reslen] = NUL;\n}",
"/*\n * Turn \"inword\" into its sound-a-like equivalent in \"res[MAXWLEN]\".\n * Multi-byte version of spell_soundfold().\n */\n static void\nspell_soundfold_wsal(slang_T *slang, char_u *inword, char_u *res)\n{\n salitem_T\t*smp = (salitem_T *)slang->sl_sal.ga_data;\n int\t\tword[MAXWLEN];\n int\t\twres[MAXWLEN];\n int\t\tl;\n char_u\t*s;\n int\t\t*ws;\n char_u\t*t;\n int\t\t*pf;\n int\t\ti, j, z;\n int\t\treslen;\n int\t\tn, k = 0;\n int\t\tz0;\n int\t\tk0;\n int\t\tn0;\n int\t\tc;\n int\t\tpri;\n int\t\tp0 = -333;\n int\t\tc0;\n int\t\tdid_white = FALSE;\n int\t\twordlen;",
"\n /*\n * Convert the multi-byte string to a wide-character string.\n * Remove accents, if wanted. We actually remove all non-word characters.\n * But keep white space.\n */\n wordlen = 0;\n for (s = inword; *s != NUL; )\n {\n\tt = s;\n\tc = mb_cptr2char_adv(&s);\n\tif (slang->sl_rem_accents)\n\t{\n\t if (enc_utf8 ? utf_class(c) == 0 : VIM_ISWHITE(c))\n\t {\n\t\tif (did_white)\n\t\t continue;\n\t\tc = ' ';\n\t\tdid_white = TRUE;\n\t }\n\t else\n\t {\n\t\tdid_white = FALSE;\n\t\tif (!spell_iswordp_nmw(t, curwin))\n\t\t continue;\n\t }\n\t}\n\tword[wordlen++] = c;\n }\n word[wordlen] = NUL;",
" /*\n * This algorithm comes from Aspell phonet.cpp.\n * Converted from C++ to C. Added support for multi-byte chars.\n * Changed to keep spaces.\n */\n i = reslen = z = 0;\n while ((c = word[i]) != NUL)\n {\n\t// Start with the first rule that has the character in the word.\n\tn = slang->sl_sal_first[c & 0xff];\n\tz0 = 0;",
"\tif (n >= 0)\n\t{\n\t // Check all rules for the same index byte.\n\t // If c is 0x300 need extra check for the end of the array, as\n\t // (c & 0xff) is NUL.\n\t for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff)\n\t\t\t\t\t\t\t && ws[0] != NUL; ++n)\n\t {\n\t\t// Quickly skip entries that don't match the word. Most\n\t\t// entries are less than three chars, optimize for that.\n\t\tif (c != ws[0])\n\t\t continue;\n\t\tk = smp[n].sm_leadlen;\n\t\tif (k > 1)\n\t\t{\n\t\t if (word[i + 1] != ws[1])\n\t\t\tcontinue;\n\t\t if (k > 2)\n\t\t {\n\t\t\tfor (j = 2; j < k; ++j)\n\t\t\t if (word[i + j] != ws[j])\n\t\t\t\tbreak;\n\t\t\tif (j < k)\n\t\t\t continue;\n\t\t }\n\t\t}",
"\t\tif ((pf = smp[n].sm_oneof_w) != NULL)\n\t\t{\n\t\t // Check for match with one of the chars in \"sm_oneof\".\n\t\t while (*pf != NUL && *pf != word[i + k])\n\t\t\t++pf;\n\t\t if (*pf == NUL)\n\t\t\tcontinue;\n\t\t ++k;\n\t\t}\n\t\ts = smp[n].sm_rules;\n\t\tpri = 5; // default priority",
"\t\tp0 = *s;\n\t\tk0 = k;\n\t\twhile (*s == '-' && k > 1)\n\t\t{\n\t\t k--;\n\t\t s++;\n\t\t}\n\t\tif (*s == '<')\n\t\t s++;\n\t\tif (VIM_ISDIGIT(*s))\n\t\t{\n\t\t // determine priority\n\t\t pri = *s - '0';\n\t\t s++;\n\t\t}\n\t\tif (*s == '^' && *(s + 1) == '^')\n\t\t s++;",
"\t\tif (*s == NUL\n\t\t\t|| (*s == '^'\n\t\t\t && (i == 0 || !(word[i - 1] == ' '\n\t\t\t\t || spell_iswordp_w(word + i - 1, curwin)))\n\t\t\t && (*(s + 1) != '$'\n\t\t\t\t|| (!spell_iswordp_w(word + i + k0, curwin))))\n\t\t\t|| (*s == '$' && i > 0\n\t\t\t && spell_iswordp_w(word + i - 1, curwin)\n\t\t\t && (!spell_iswordp_w(word + i + k0, curwin))))\n\t\t{\n\t\t // search for followup rules, if:\n\t\t // followup and k > 1 and NO '-' in searchstring\n\t\t c0 = word[i + k - 1];\n\t\t n0 = slang->sl_sal_first[c0 & 0xff];",
"\t\t if (slang->sl_followup && k > 1 && n0 >= 0\n\t\t\t\t\t && p0 != '-' && word[i + k] != NUL)\n\t\t {\n\t\t\t// Test follow-up rule for \"word[i + k]\"; loop over\n\t\t\t// all entries with the same index byte.\n\t\t\tfor ( ; ((ws = smp[n0].sm_lead_w)[0] & 0xff)\n\t\t\t\t\t\t\t == (c0 & 0xff); ++n0)\n\t\t\t{\n\t\t\t // Quickly skip entries that don't match the word.\n\t\t\t if (c0 != ws[0])\n\t\t\t\tcontinue;\n\t\t\t k0 = smp[n0].sm_leadlen;\n\t\t\t if (k0 > 1)\n\t\t\t {\n\t\t\t\tif (word[i + k] != ws[1])\n\t\t\t\t continue;\n\t\t\t\tif (k0 > 2)\n\t\t\t\t{\n\t\t\t\t pf = word + i + k + 1;\n\t\t\t\t for (j = 2; j < k0; ++j)\n\t\t\t\t\tif (*pf++ != ws[j])\n\t\t\t\t\t break;\n\t\t\t\t if (j < k0)\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t }\n\t\t\t k0 += k - 1;",
"\t\t\t if ((pf = smp[n0].sm_oneof_w) != NULL)\n\t\t\t {\n\t\t\t\t// Check for match with one of the chars in\n\t\t\t\t// \"sm_oneof\".\n\t\t\t\twhile (*pf != NUL && *pf != word[i + k0])\n\t\t\t\t ++pf;\n\t\t\t\tif (*pf == NUL)\n\t\t\t\t continue;\n\t\t\t\t++k0;\n\t\t\t }",
"\t\t\t p0 = 5;\n\t\t\t s = smp[n0].sm_rules;\n\t\t\t while (*s == '-')\n\t\t\t {\n\t\t\t\t// \"k0\" gets NOT reduced because\n\t\t\t\t// \"if (k0 == k)\"\n\t\t\t\ts++;\n\t\t\t }\n\t\t\t if (*s == '<')\n\t\t\t\ts++;\n\t\t\t if (VIM_ISDIGIT(*s))\n\t\t\t {\n\t\t\t\tp0 = *s - '0';\n\t\t\t\ts++;\n\t\t\t }",
"\t\t\t if (*s == NUL\n\t\t\t\t // *s == '^' cuts\n\t\t\t\t || (*s == '$'\n\t\t\t\t\t && !spell_iswordp_w(word + i + k0,\n\t\t\t\t\t\t\t\t curwin)))\n\t\t\t {\n\t\t\t\tif (k0 == k)\n\t\t\t\t // this is just a piece of the string\n\t\t\t\t continue;",
"\t\t\t\tif (p0 < pri)\n\t\t\t\t // priority too low\n\t\t\t\t continue;\n\t\t\t\t// rule fits; stop search\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}",
"\t\t\tif (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff)\n\t\t\t\t\t\t\t == (c0 & 0xff))\n\t\t\t continue;\n\t\t }",
"\t\t // replace string\n\t\t ws = smp[n].sm_to_w;\n\t\t s = smp[n].sm_rules;\n\t\t p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0;\n\t\t if (p0 == 1 && z == 0)\n\t\t {\n\t\t\t// rule with '<' is used\n\t\t\tif (reslen > 0 && ws != NULL && *ws != NUL\n\t\t\t\t&& (wres[reslen - 1] == c\n\t\t\t\t\t\t || wres[reslen - 1] == *ws))\n\t\t\t reslen--;\n\t\t\tz0 = 1;\n\t\t\tz = 1;\n\t\t\tk0 = 0;\n\t\t\tif (ws != NULL)\n\t\t\t while (*ws != NUL && word[i + k0] != NUL)\n\t\t\t {\n\t\t\t\tword[i + k0] = *ws;\n\t\t\t\tk0++;\n\t\t\t\tws++;\n\t\t\t }\n\t\t\tif (k > k0)\n\t\t\t mch_memmove(word + i + k0, word + i + k,\n\t\t\t\t sizeof(int) * (wordlen - (i + k) + 1));",
"\t\t\t// new \"actual letter\"\n\t\t\tc = word[i];\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// no '<' rule used\n\t\t\ti += k - 1;\n\t\t\tz = 0;\n\t\t\tif (ws != NULL)\n\t\t\t while (*ws != NUL && ws[1] != NUL\n\t\t\t\t\t\t\t && reslen < MAXWLEN)\n\t\t\t {\n\t\t\t\tif (reslen == 0 || wres[reslen - 1] != *ws)\n\t\t\t\t wres[reslen++] = *ws;\n\t\t\t\tws++;\n\t\t\t }\n\t\t\t// new \"actual letter\"\n\t\t\tif (ws == NULL)\n\t\t\t c = NUL;\n\t\t\telse\n\t\t\t c = *ws;\n\t\t\tif (strstr((char *)s, \"^^\") != NULL)\n\t\t\t{\n\t\t\t if (c != NUL)\n\t\t\t\twres[reslen++] = c;\n\t\t\t mch_memmove(word, word + i + 1,\n\t\t\t\t sizeof(int) * (wordlen - (i + 1) + 1));\n\t\t\t i = 0;\n\t\t\t z0 = 1;\n\t\t\t}\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\t}\n\telse if (VIM_ISWHITE(c))\n\t{\n\t c = ' ';\n\t k = 1;\n\t}",
"\tif (z0 == 0)\n\t{\n\t if (k && !p0 && reslen < MAXWLEN && c != NUL\n\t\t && (!slang->sl_collapse || reslen == 0\n\t\t\t\t\t\t || wres[reslen - 1] != c))\n\t\t// condense only double letters\n\t\twres[reslen++] = c;",
"\t i++;\n\t z = 0;\n\t k = 0;\n\t}\n }",
" // Convert wide characters in \"wres\" to a multi-byte string in \"res\".\n l = 0;\n for (n = 0; n < reslen; ++n)\n {\n\tl += mb_char2bytes(wres[n], res + l);\n\tif (l + MB_MAXBYTES > MAXWLEN)\n\t break;\n }\n res[l] = NUL;\n}",
"/*\n * \":spellinfo\"\n */\n void\nex_spellinfo(exarg_T *eap UNUSED)\n{\n int\t\tlpi;\n langp_T\t*lp;\n char_u\t*p;",
" if (no_spell_checking(curwin))\n\treturn;",
" msg_start();\n for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len && !got_int; ++lpi)\n {\n\tlp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\tmsg_puts(\"file: \");\n\tmsg_puts((char *)lp->lp_slang->sl_fname);\n\tmsg_putchar('\\n');\n\tp = lp->lp_slang->sl_info;\n\tif (p != NULL)\n\t{\n\t msg_puts((char *)p);\n\t msg_putchar('\\n');\n\t}\n }\n msg_end();\n}",
"#define DUMPFLAG_KEEPCASE 1\t// round 2: keep-case tree\n#define DUMPFLAG_COUNT\t 2\t// include word count\n#define DUMPFLAG_ICASE\t 4\t// ignore case when finding matches\n#define DUMPFLAG_ONECAP\t 8\t// pattern starts with capital\n#define DUMPFLAG_ALLCAP\t 16\t// pattern is all capitals",
"/*\n * \":spelldump\"\n */\n void\nex_spelldump(exarg_T *eap)\n{\n char_u *spl;\n long dummy;",
" if (no_spell_checking(curwin))\n\treturn;\n (void)get_option_value((char_u*)\"spl\", &dummy, &spl, NULL, OPT_LOCAL);",
" // Create a new empty buffer in a new window.\n do_cmdline_cmd((char_u *)\"new\");",
" // enable spelling locally in the new window\n set_option_value_give_err((char_u*)\"spell\", TRUE, (char_u*)\"\", OPT_LOCAL);\n set_option_value_give_err((char_u*)\"spl\", dummy, spl, OPT_LOCAL);\n vim_free(spl);",
" if (!BUFEMPTY())\n\treturn;",
" spell_dump_compl(NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0);",
" // Delete the empty line that we started with.\n if (curbuf->b_ml.ml_line_count > 1)\n\tml_delete(curbuf->b_ml.ml_line_count);",
" redraw_later(NOT_VALID);\n}",
"/*\n * Go through all possible words and:\n * 1. When \"pat\" is NULL: dump a list of all words in the current buffer.\n *\t\"ic\" and \"dir\" are not used.\n * 2. When \"pat\" is not NULL: add matching words to insert mode completion.\n */\n void\nspell_dump_compl(\n char_u\t*pat,\t // leading part of the word\n int\t\tic,\t // ignore case\n int\t\t*dir,\t // direction for adding matches\n int\t\tdumpflags_arg)\t// DUMPFLAG_*\n{\n langp_T\t*lp;\n slang_T\t*slang;\n idx_T\tarridx[MAXWLEN];\n int\t\tcuri[MAXWLEN];\n char_u\tword[MAXWLEN];\n int\t\tc;\n char_u\t*byts;\n idx_T\t*idxs;\n linenr_T\tlnum = 0;\n int\t\tround;\n int\t\tdepth;\n int\t\tn;\n int\t\tflags;\n char_u\t*region_names = NULL;\t // region names being used\n int\t\tdo_region = TRUE;\t // dump region names and numbers\n char_u\t*p;\n int\t\tlpi;\n int\t\tdumpflags = dumpflags_arg;\n int\t\tpatlen;",
" // When ignoring case or when the pattern starts with capital pass this on\n // to dump_word().\n if (pat != NULL)\n {\n\tif (ic)\n\t dumpflags |= DUMPFLAG_ICASE;\n\telse\n\t{\n\t n = captype(pat, NULL);\n\t if (n == WF_ONECAP)\n\t\tdumpflags |= DUMPFLAG_ONECAP;\n\t else if (n == WF_ALLCAP && (int)STRLEN(pat) > mb_ptr2len(pat))\n\t\tdumpflags |= DUMPFLAG_ALLCAP;\n\t}\n }",
" // Find out if we can support regions: All languages must support the same\n // regions or none at all.\n for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)\n {\n\tlp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\tp = lp->lp_slang->sl_regions;\n\tif (p[0] != 0)\n\t{\n\t if (region_names == NULL)\t // first language with regions\n\t\tregion_names = p;\n\t else if (STRCMP(region_names, p) != 0)\n\t {\n\t\tdo_region = FALSE;\t // region names are different\n\t\tbreak;\n\t }\n\t}\n }",
" if (do_region && region_names != NULL)\n {\n\tif (pat == NULL)\n\t{\n\t vim_snprintf((char *)IObuff, IOSIZE, \"/regions=%s\", region_names);\n\t ml_append(lnum++, IObuff, (colnr_T)0, FALSE);\n\t}\n }\n else\n\tdo_region = FALSE;",
" /*\n * Loop over all files loaded for the entries in 'spelllang'.\n */\n for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)\n {\n\tlp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\tslang = lp->lp_slang;\n\tif (slang->sl_fbyts == NULL)\t // reloading failed\n\t continue;",
"\tif (pat == NULL)\n\t{\n\t vim_snprintf((char *)IObuff, IOSIZE, \"# file: %s\", slang->sl_fname);\n\t ml_append(lnum++, IObuff, (colnr_T)0, FALSE);\n\t}",
"\t// When matching with a pattern and there are no prefixes only use\n\t// parts of the tree that match \"pat\".\n\tif (pat != NULL && slang->sl_pbyts == NULL)\n\t patlen = (int)STRLEN(pat);\n\telse\n\t patlen = -1;",
"\t// round 1: case-folded tree\n\t// round 2: keep-case tree\n\tfor (round = 1; round <= 2; ++round)\n\t{\n\t if (round == 1)\n\t {\n\t\tdumpflags &= ~DUMPFLAG_KEEPCASE;\n\t\tbyts = slang->sl_fbyts;\n\t\tidxs = slang->sl_fidxs;\n\t }\n\t else\n\t {\n\t\tdumpflags |= DUMPFLAG_KEEPCASE;\n\t\tbyts = slang->sl_kbyts;\n\t\tidxs = slang->sl_kidxs;\n\t }\n\t if (byts == NULL)\n\t\tcontinue;\t\t// array is empty",
"\t depth = 0;\n\t arridx[0] = 0;\n\t curi[0] = 1;\n\t while (depth >= 0 && !got_int\n\t\t\t\t && (pat == NULL || !ins_compl_interrupted()))\n\t {\n\t\tif (curi[depth] > byts[arridx[depth]])\n\t\t{\n\t\t // Done all bytes at this node, go up one level.\n\t\t --depth;\n\t\t line_breakcheck();\n\t\t ins_compl_check_keys(50, FALSE);\n\t\t}\n\t\telse\n\t\t{\n\t\t // Do one more byte at this node.\n\t\t n = arridx[depth] + curi[depth];\n\t\t ++curi[depth];\n\t\t c = byts[n];\n\t\t if (c == 0)\n\t\t {\n\t\t\t// End of word, deal with the word.\n\t\t\t// Don't use keep-case words in the fold-case tree,\n\t\t\t// they will appear in the keep-case tree.\n\t\t\t// Only use the word when the region matches.\n\t\t\tflags = (int)idxs[n];\n\t\t\tif ((round == 2 || (flags & WF_KEEPCAP) == 0)\n\t\t\t\t&& (flags & WF_NEEDCOMP) == 0\n\t\t\t\t&& (do_region\n\t\t\t\t || (flags & WF_REGION) == 0\n\t\t\t\t || (((unsigned)flags >> 16)\n\t\t\t\t\t\t & lp->lp_region) != 0))\n\t\t\t{\n\t\t\t word[depth] = NUL;\n\t\t\t if (!do_region)\n\t\t\t\tflags &= ~WF_REGION;",
"\t\t\t // Dump the basic word if there is no prefix or\n\t\t\t // when it's the first one.\n\t\t\t c = (unsigned)flags >> 24;\n\t\t\t if (c == 0 || curi[depth] == 2)\n\t\t\t {\n\t\t\t\tdump_word(slang, word, pat, dir,\n\t\t\t\t\t\t dumpflags, flags, lnum);\n\t\t\t\tif (pat == NULL)\n\t\t\t\t ++lnum;\n\t\t\t }",
"\t\t\t // Apply the prefix, if there is one.\n\t\t\t if (c != 0)\n\t\t\t\tlnum = dump_prefixes(slang, word, pat, dir,\n\t\t\t\t\t\t dumpflags, flags, lnum);\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// Normal char, go one level deeper.\n\t\t\tword[depth++] = c;\n\t\t\tarridx[depth] = idxs[n];\n\t\t\tcuri[depth] = 1;",
"\t\t\t// Check if this character matches with the pattern.\n\t\t\t// If not skip the whole tree below it.\n\t\t\t// Always ignore case here, dump_word() will check\n\t\t\t// proper case later. This isn't exactly right when\n\t\t\t// length changes for multi-byte characters with\n\t\t\t// ignore case...\n\t\t\tif (depth <= patlen\n\t\t\t\t\t&& MB_STRNICMP(word, pat, depth) != 0)\n\t\t\t --depth;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n}",
"/*\n * Dump one word: apply case modifications and append a line to the buffer.\n * When \"lnum\" is zero add insert mode completion.\n */\n static void\ndump_word(\n slang_T\t*slang,\n char_u\t*word,\n char_u\t*pat,\n int\t\t*dir,\n int\t\tdumpflags,\n int\t\twordflags,\n linenr_T\tlnum)\n{\n int\t\tkeepcap = FALSE;\n char_u\t*p;\n char_u\t*tw;\n char_u\tcword[MAXWLEN];\n char_u\tbadword[MAXWLEN + 10];\n int\t\ti;\n int\t\tflags = wordflags;",
" if (dumpflags & DUMPFLAG_ONECAP)\n\tflags |= WF_ONECAP;\n if (dumpflags & DUMPFLAG_ALLCAP)\n\tflags |= WF_ALLCAP;",
" if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0)\n {\n\t// Need to fix case according to \"flags\".\n\tmake_case_word(word, cword, flags);\n\tp = cword;\n }\n else\n {\n\tp = word;\n\tif ((dumpflags & DUMPFLAG_KEEPCASE)\n\t\t&& ((captype(word, NULL) & WF_KEEPCAP) == 0\n\t\t\t\t\t\t || (flags & WF_FIXCAP) != 0))\n\t keepcap = TRUE;\n }\n tw = p;",
" if (pat == NULL)\n {\n\t// Add flags and regions after a slash.\n\tif ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap)\n\t{\n\t STRCPY(badword, p);\n\t STRCAT(badword, \"/\");\n\t if (keepcap)\n\t\tSTRCAT(badword, \"=\");\n\t if (flags & WF_BANNED)\n\t\tSTRCAT(badword, \"!\");\n\t else if (flags & WF_RARE)\n\t\tSTRCAT(badword, \"?\");\n\t if (flags & WF_REGION)\n\t\tfor (i = 0; i < 7; ++i)\n\t\t if (flags & (0x10000 << i))\n\t\t\tsprintf((char *)badword + STRLEN(badword), \"%d\", i + 1);\n\t p = badword;\n\t}",
"\tif (dumpflags & DUMPFLAG_COUNT)\n\t{\n\t hashitem_T *hi;",
"\t // Include the word count for \":spelldump!\".\n\t hi = hash_find(&slang->sl_wordcount, tw);\n\t if (!HASHITEM_EMPTY(hi))\n\t {\n\t\tvim_snprintf((char *)IObuff, IOSIZE, \"%s\\t%d\",\n\t\t\t\t\t\t tw, HI2WC(hi)->wc_count);\n\t\tp = IObuff;\n\t }\n\t}",
"\tml_append(lnum, p, (colnr_T)0, FALSE);\n }\n else if (((dumpflags & DUMPFLAG_ICASE)\n\t\t ? MB_STRNICMP(p, pat, STRLEN(pat)) == 0\n\t\t : STRNCMP(p, pat, STRLEN(pat)) == 0)\n\t\t&& ins_compl_add_infercase(p, (int)STRLEN(p),\n\t\t\t\t\t p_ic, NULL, *dir, FALSE) == OK)\n\t// if dir was BACKWARD then honor it just once\n\t*dir = FORWARD;\n}",
"/*\n * For \":spelldump\": Find matching prefixes for \"word\". Prepend each to\n * \"word\" and append a line to the buffer.\n * When \"lnum\" is zero add insert mode completion.\n * Return the updated line number.\n */\n static linenr_T\ndump_prefixes(\n slang_T\t*slang,\n char_u\t*word,\t // case-folded word\n char_u\t*pat,\n int\t\t*dir,\n int\t\tdumpflags,\n int\t\tflags,\t // flags with prefix ID\n linenr_T\tstartlnum)\n{\n idx_T\tarridx[MAXWLEN];\n int\t\tcuri[MAXWLEN];\n char_u\tprefix[MAXWLEN];\n char_u\tword_up[MAXWLEN];\n int\t\thas_word_up = FALSE;\n int\t\tc;\n char_u\t*byts;\n idx_T\t*idxs;\n linenr_T\tlnum = startlnum;\n int\t\tdepth;\n int\t\tn;\n int\t\tlen;\n int\t\ti;",
" // If the word starts with a lower-case letter make the word with an\n // upper-case letter in word_up[].\n c = PTR2CHAR(word);\n if (SPELL_TOUPPER(c) != c)\n {\n\tonecap_copy(word, word_up, TRUE);\n\thas_word_up = TRUE;\n }",
" byts = slang->sl_pbyts;\n idxs = slang->sl_pidxs;\n if (byts != NULL)\t\t// array not is empty\n {\n\t/*\n\t * Loop over all prefixes, building them byte-by-byte in prefix[].\n\t * When at the end of a prefix check that it supports \"flags\".\n\t */\n\tdepth = 0;\n\tarridx[0] = 0;\n\tcuri[0] = 1;\n\twhile (depth >= 0 && !got_int)\n\t{\n\t n = arridx[depth];\n\t len = byts[n];\n\t if (curi[depth] > len)\n\t {\n\t\t// Done all bytes at this node, go up one level.\n\t\t--depth;\n\t\tline_breakcheck();\n\t }\n\t else\n\t {\n\t\t// Do one more byte at this node.\n\t\tn += curi[depth];\n\t\t++curi[depth];\n\t\tc = byts[n];\n\t\tif (c == 0)\n\t\t{\n\t\t // End of prefix, find out how many IDs there are.\n\t\t for (i = 1; i < len; ++i)\n\t\t\tif (byts[n + i] != 0)\n\t\t\t break;\n\t\t curi[depth] += i - 1;",
"\t\t c = valid_word_prefix(i, n, flags, word, slang, FALSE);\n\t\t if (c != 0)\n\t\t {\n\t\t\tvim_strncpy(prefix + depth, word, MAXWLEN - depth - 1);\n\t\t\tdump_word(slang, prefix, pat, dir, dumpflags,\n\t\t\t\t(c & WF_RAREPFX) ? (flags | WF_RARE)\n\t\t\t\t\t\t\t : flags, lnum);\n\t\t\tif (lnum != 0)\n\t\t\t ++lnum;\n\t\t }",
"\t\t // Check for prefix that matches the word when the\n\t\t // first letter is upper-case, but only if the prefix has\n\t\t // a condition.\n\t\t if (has_word_up)\n\t\t {\n\t\t\tc = valid_word_prefix(i, n, flags, word_up, slang,\n\t\t\t\t\t\t\t\t\tTRUE);\n\t\t\tif (c != 0)\n\t\t\t{\n\t\t\t vim_strncpy(prefix + depth, word_up,\n\t\t\t\t\t\t\t MAXWLEN - depth - 1);\n\t\t\t dump_word(slang, prefix, pat, dir, dumpflags,\n\t\t\t\t (c & WF_RAREPFX) ? (flags | WF_RARE)\n\t\t\t\t\t\t\t : flags, lnum);\n\t\t\t if (lnum != 0)\n\t\t\t\t++lnum;\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t // Normal char, go one level deeper.\n\t\t prefix[depth++] = c;\n\t\t arridx[depth] = idxs[n];\n\t\t curi[depth] = 1;\n\t\t}\n\t }\n\t}\n }",
" return lnum;\n}",
"/*\n * Move \"p\" to the end of word \"start\".\n * Uses the spell-checking word characters.\n */\n char_u *\nspell_to_word_end(char_u *start, win_T *win)\n{\n char_u *p = start;",
" while (*p != NUL && spell_iswordp(p, win))\n\tMB_PTR_ADV(p);\n return p;\n}",
"/*\n * For Insert mode completion CTRL-X s:\n * Find start of the word in front of column \"startcol\".\n * We don't check if it is badly spelled, with completion we can only change\n * the word in front of the cursor.\n * Returns the column number of the word.\n */\n int\nspell_word_start(int startcol)\n{\n char_u\t*line;\n char_u\t*p;\n int\t\tcol = 0;",
" if (no_spell_checking(curwin))\n\treturn startcol;",
" // Find a word character before \"startcol\".\n line = ml_get_curline();\n for (p = line + startcol; p > line; )\n {\n\tMB_PTR_BACK(line, p);\n\tif (spell_iswordp_nmw(p, curwin))\n\t break;\n }",
" // Go back to start of the word.\n while (p > line)\n {\n\tcol = (int)(p - line);\n\tMB_PTR_BACK(line, p);\n\tif (!spell_iswordp(p, curwin))\n\t break;\n\tcol = 0;\n }",
" return col;\n}",
"/*\n * Need to check for 'spellcapcheck' now, the word is removed before\n * expand_spelling() is called. Therefore the ugly global variable.\n */\nstatic int spell_expand_need_cap;",
" void\nspell_expand_check_cap(colnr_T col)\n{\n spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col);\n}",
"/*\n * Get list of spelling suggestions.\n * Used for Insert mode completion CTRL-X ?.\n * Returns the number of matches. The matches are in \"matchp[]\", array of\n * allocated strings.\n */\n int\nexpand_spelling(\n linenr_T\tlnum UNUSED,\n char_u\t*pat,\n char_u\t***matchp)\n{\n garray_T\tga;",
" spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, TRUE);\n *matchp = ga.ga_data;\n return ga.ga_len;\n}",
"/*\n * Return TRUE if \"val\" is a valid 'spelllang' value.\n */\n int\nvalid_spelllang(char_u *val)\n{\n return valid_name(val, \".-_,@\");\n}",
"/*\n * Return TRUE if \"val\" is a valid 'spellfile' value.\n */\n int\nvalid_spellfile(char_u *val)\n{\n char_u *s;",
" for (s = val; *s != NUL; ++s)\n\tif (!vim_isfilec(*s) && *s != ',' && *s != ' ')\n\t return FALSE;\n return TRUE;\n}",
"/*\n * Handle side effects of setting 'spell'.\n * Return an error message or NULL for success.\n */\n char *\ndid_set_spell_option(int is_spellfile)\n{\n char *errmsg = NULL;\n win_T *wp;\n int\t l;",
" if (is_spellfile)\n {\n\tl = (int)STRLEN(curwin->w_s->b_p_spf);\n\tif (l > 0 && (l < 4\n\t\t\t|| STRCMP(curwin->w_s->b_p_spf + l - 4, \".add\") != 0))\n\t errmsg = e_invalid_argument;\n }",
" if (errmsg == NULL)\n {\n\tFOR_ALL_WINDOWS(wp)\n\t if (wp->w_buffer == curbuf && wp->w_p_spell)\n\t {\n\t\terrmsg = did_set_spelllang(wp);\n\t\tbreak;\n\t }\n }\n return errmsg;\n}",
"/*\n * Set curbuf->b_cap_prog to the regexp program for 'spellcapcheck'.\n * Return error message when failed, NULL when OK.\n */\n char *\ncompile_cap_prog(synblock_T *synblock)\n{\n regprog_T *rp = synblock->b_cap_prog;\n char_u\t*re;",
" if (synblock->b_p_spc == NULL || *synblock->b_p_spc == NUL)\n\tsynblock->b_cap_prog = NULL;\n else\n {\n\t// Prepend a ^ so that we only match at one column\n\tre = concat_str((char_u *)\"^\", synblock->b_p_spc);\n\tif (re != NULL)\n\t{\n\t synblock->b_cap_prog = vim_regcomp(re, RE_MAGIC);\n\t vim_free(re);\n\t if (synblock->b_cap_prog == NULL)\n\t {\n\t\tsynblock->b_cap_prog = rp; // restore the previous program\n\t\treturn e_invalid_argument;\n\t }\n\t}\n }",
" vim_regfree(rp);\n return NULL;\n}",
"#endif // FEAT_SPELL"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
0,
1,
1,
1,
1,
1,
1,
0,
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1491, 804, 736], "buggy_code_start_loc": [1278, 804, 736], "filenames": ["src/spell.c", "src/testdir/test_spell_utf8.vim", "src/version.c"], "fixing_code_end_loc": [1495, 820, 739], "fixing_code_start_loc": [1278, 805, 737], "message": "Use After Free in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B6CDC65-37D1-4A6A-B6C5-7B58DC5757ED", "versionEndExcluding": "8.2.5072", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "0146DEE5-EF72-48C3-9DDD-28EA3595BDD1", "versionEndExcluding": "11.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7B7BC361-3A04-4C88-A3AE-82B9993A73A0", "versionEndExcluding": "12.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use After Free in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Un Uso de Memoria Previamente Liberada en el repositorio GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2042", "lastModified": "2023-05-03T12:15:40.820", "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": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 0.8, "impactScore": 6.0, "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-06-10T19:15:08.813", "references": [{"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/28"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/41"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/43"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/45"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/8628b4cd-4055-4059-aed4-64f7fdc10eba"}, {"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"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213443"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213444"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213488"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, "type": "CWE-416"}
| 317
|
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 * spell.c: code for spell checking\n *\n * See spellfile.c for the Vim spell file format.\n *\n * The spell checking mechanism uses a tree (aka trie). Each node in the tree\n * has a list of bytes that can appear (siblings). For each byte there is a\n * pointer to the node with the byte that follows in the word (child).\n *\n * A NUL byte is used where the word may end. The bytes are sorted, so that\n * binary searching can be used and the NUL bytes are at the start. The\n * number of possible bytes is stored before the list of bytes.\n *\n * The tree uses two arrays: \"byts\" stores the characters, \"idxs\" stores\n * either the next index or flags. The tree starts at index 0. For example,\n * to lookup \"vi\" this sequence is followed:\n *\ti = 0\n *\tlen = byts[i]\n *\tn = where \"v\" appears in byts[i + 1] to byts[i + len]\n *\ti = idxs[n]\n *\tlen = byts[i]\n *\tn = where \"i\" appears in byts[i + 1] to byts[i + len]\n *\ti = idxs[n]\n *\tlen = byts[i]\n *\tfind that byts[i + 1] is 0, idxs[i + 1] has flags for \"vi\".\n *\n * There are two word trees: one with case-folded words and one with words in\n * original case. The second one is only used for keep-case words and is\n * usually small.\n *\n * There is one additional tree for when not all prefixes are applied when\n * generating the .spl file. This tree stores all the possible prefixes, as\n * if they were words. At each word (prefix) end the prefix nr is stored, the\n * following word must support this prefix nr. And the condition nr is\n * stored, used to lookup the condition that the word must match with.\n *\n * Thanks to Olaf Seibert for providing an example implementation of this tree\n * and the compression mechanism.\n * LZ trie ideas:\n *\thttp://www.irb.hr/hr/home/ristov/papers/RistovLZtrieRevision1.pdf\n * More papers: http://www-igm.univ-mlv.fr/~laporte/publi_en.html\n *\n * Matching involves checking the caps type: Onecap ALLCAP KeepCap.\n *\n * Why doesn't Vim use aspell/ispell/myspell/etc.?\n * See \":help develop-spell\".\n */",
"#define IN_SPELL_C\n#include \"vim.h\"",
"#if defined(FEAT_SPELL) || defined(PROTO)",
"#ifndef UNIX\t\t// it's in os_unix.h for Unix\n# include <time.h>\t// for time_t\n#endif",
"#define REGION_ALL 0xff\t\t// word valid in all regions",
"// Result values. Lower number is accepted over higher one.\n#define SP_BANNED\t(-1)\n#define SP_OK\t\t0\n#define SP_RARE\t\t1\n#define SP_LOCAL\t2\n#define SP_BAD\t\t3",
"/*\n * Structure to store info for word matching.\n */\ntypedef struct matchinf_S\n{\n langp_T\t*mi_lp;\t\t\t// info for language and region",
" // pointers to original text to be checked\n char_u\t*mi_word;\t\t// start of word being checked\n char_u\t*mi_end;\t\t// end of matching word so far\n char_u\t*mi_fend;\t\t// next char to be added to mi_fword\n char_u\t*mi_cend;\t\t// char after what was used for\n\t\t\t\t\t// mi_capflags",
" // case-folded text\n char_u\tmi_fword[MAXWLEN + 1];\t// mi_word case-folded\n int\t\tmi_fwordlen;\t\t// nr of valid bytes in mi_fword",
" // for when checking word after a prefix\n int\t\tmi_prefarridx;\t\t// index in sl_pidxs with list of\n\t\t\t\t\t// affixID/condition\n int\t\tmi_prefcnt;\t\t// number of entries at mi_prefarridx\n int\t\tmi_prefixlen;\t\t// byte length of prefix\n int\t\tmi_cprefixlen;\t\t// byte length of prefix in original\n\t\t\t\t\t// case",
" // for when checking a compound word\n int\t\tmi_compoff;\t\t// start of following word offset\n char_u\tmi_compflags[MAXWLEN];\t// flags for compound words used\n int\t\tmi_complen;\t\t// nr of compound words used\n int\t\tmi_compextra;\t\t// nr of COMPOUNDROOT words",
" // others\n int\t\tmi_result;\t\t// result so far: SP_BAD, SP_OK, etc.\n int\t\tmi_capflags;\t\t// WF_ONECAP WF_ALLCAP WF_KEEPCAP\n win_T\t*mi_win;\t\t// buffer being checked",
" // for NOBREAK\n int\t\tmi_result2;\t\t// \"mi_resul\" without following word\n char_u\t*mi_end2;\t\t// \"mi_end\" without following word\n} matchinf_T;",
"\nstatic int spell_mb_isword_class(int cl, win_T *wp);",
"// mode values for find_word\n#define FIND_FOLDWORD\t 0\t// find word case-folded\n#define FIND_KEEPWORD\t 1\t// find keep-case word\n#define FIND_PREFIX\t 2\t// find word after prefix\n#define FIND_COMPOUND\t 3\t// find case-folded compound word\n#define FIND_KEEPCOMPOUND 4\t// find keep-case compound word",
"static void find_word(matchinf_T *mip, int mode);\nstatic void find_prefix(matchinf_T *mip, int mode);\nstatic int fold_more(matchinf_T *mip);\nstatic void spell_load_cb(char_u *fname, void *cookie);\nstatic int count_syllables(slang_T *slang, char_u *word);\nstatic void clear_midword(win_T *buf);\nstatic void use_midword(slang_T *lp, win_T *buf);\nstatic int find_region(char_u *rp, char_u *region);\nstatic void spell_soundfold_sofo(slang_T *slang, char_u *inword, char_u *res);\nstatic void spell_soundfold_sal(slang_T *slang, char_u *inword, char_u *res);\nstatic void spell_soundfold_wsal(slang_T *slang, char_u *inword, char_u *res);\nstatic void dump_word(slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T lnum);\nstatic linenr_T dump_prefixes(slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T startlnum);",
"/*\n * Main spell-checking function.\n * \"ptr\" points to a character that could be the start of a word.\n * \"*attrp\" is set to the highlight index for a badly spelled word. For a\n * non-word or when it's OK it remains unchanged.\n * This must only be called when 'spelllang' is not empty.\n *\n * \"capcol\" is used to check for a Capitalised word after the end of a\n * sentence. If it's zero then perform the check. Return the column where to\n * check next, or -1 when no sentence end was found. If it's NULL then don't\n * worry.\n *\n * Returns the length of the word in bytes, also when it's OK, so that the\n * caller can skip over the word.\n */\n int\nspell_check(\n win_T\t*wp,\t\t// current window\n char_u\t*ptr,\n hlf_T\t*attrp,\n int\t\t*capcol,\t// column to check for Capital\n int\t\tdocount)\t// count good words\n{\n matchinf_T\tmi;\t\t// Most things are put in \"mi\" so that it can\n\t\t\t\t// be passed to functions quickly.\n int\t\tnrlen = 0;\t// found a number first\n int\t\tc;\n int\t\twrongcaplen = 0;\n int\t\tlpi;\n int\t\tcount_word = docount;\n int\t\tuse_camel_case = *wp->w_s->b_p_spo != NUL;\n int\t\tcamel_case = 0;",
" // A word never starts at a space or a control character. Return quickly\n // then, skipping over the character.\n if (*ptr <= ' ')\n\treturn 1;",
" // Return here when loading language files failed.\n if (wp->w_s->b_langp.ga_len == 0)\n\treturn 1;",
" CLEAR_FIELD(mi);",
" // A number is always OK. Also skip hexadecimal numbers 0xFF99 and\n // 0X99FF. But always do check spelling to find \"3GPP\" and \"11\n // julifeest\".\n if (*ptr >= '0' && *ptr <= '9')\n {\n\tif (*ptr == '0' && (ptr[1] == 'b' || ptr[1] == 'B'))\n\t mi.mi_end = skipbin(ptr + 2);\n\telse if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X'))\n\t mi.mi_end = skiphex(ptr + 2);\n\telse\n\t mi.mi_end = skipdigits(ptr);\n\tnrlen = (int)(mi.mi_end - ptr);\n }",
" // Find the normal end of the word (until the next non-word character).\n mi.mi_word = ptr;\n mi.mi_fend = ptr;\n if (spell_iswordp(mi.mi_fend, wp))\n {\n\tint prev_upper;\n\tint this_upper = FALSE; // init for gcc",
"\tif (use_camel_case)\n\t{\n\t c = PTR2CHAR(mi.mi_fend);\n\t this_upper = SPELL_ISUPPER(c);\n\t}",
"\tdo\n\t{\n\t MB_PTR_ADV(mi.mi_fend);\n\t if (use_camel_case)\n\t {\n\t\tprev_upper = this_upper;\n\t\tc = PTR2CHAR(mi.mi_fend);\n\t\tthis_upper = SPELL_ISUPPER(c);\n\t\tcamel_case = !prev_upper && this_upper;\n\t }\n\t} while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp)\n\t\t\t\t\t\t\t && !camel_case);",
"\tif (capcol != NULL && *capcol == 0 && wp->w_s->b_cap_prog != NULL)\n\t{\n\t // Check word starting with capital letter.\n\t c = PTR2CHAR(ptr);\n\t if (!SPELL_ISUPPER(c))\n\t\twrongcaplen = (int)(mi.mi_fend - ptr);\n\t}\n }\n if (capcol != NULL)\n\t*capcol = -1;",
" // We always use the characters up to the next non-word character,\n // also for bad words.\n mi.mi_end = mi.mi_fend;",
" // Check caps type later.\n mi.mi_capflags = 0;\n mi.mi_cend = NULL;\n mi.mi_win = wp;",
" // case-fold the word with one non-word character, so that we can check\n // for the word end.\n if (*mi.mi_fend != NUL)\n\tMB_PTR_ADV(mi.mi_fend);",
" (void)spell_casefold(wp, ptr, (int)(mi.mi_fend - ptr), mi.mi_fword,\n\t\t\t\t\t\t\t MAXWLEN + 1);\n mi.mi_fwordlen = (int)STRLEN(mi.mi_fword);",
" if (camel_case && mi.mi_fwordlen > 0)\n\t// Introduce a fake word end space into the folded word.\n\tmi.mi_fword[mi.mi_fwordlen - 1] = ' ';",
" // The word is bad unless we recognize it.\n mi.mi_result = SP_BAD;\n mi.mi_result2 = SP_BAD;",
" /*\n * Loop over the languages specified in 'spelllang'.\n * We check them all, because a word may be matched longer in another\n * language.\n */\n for (lpi = 0; lpi < wp->w_s->b_langp.ga_len; ++lpi)\n {\n\tmi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, lpi);",
"\t// If reloading fails the language is still in the list but everything\n\t// has been cleared.\n\tif (mi.mi_lp->lp_slang->sl_fidxs == NULL)\n\t continue;",
"\t// Check for a matching word in case-folded words.\n\tfind_word(&mi, FIND_FOLDWORD);",
"\t// Check for a matching word in keep-case words.\n\tfind_word(&mi, FIND_KEEPWORD);",
"\t// Check for matching prefixes.\n\tfind_prefix(&mi, FIND_FOLDWORD);",
"\t// For a NOBREAK language, may want to use a word without a following\n\t// word as a backup.\n\tif (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD\n\t\t\t\t\t\t && mi.mi_result2 != SP_BAD)\n\t{\n\t mi.mi_result = mi.mi_result2;\n\t mi.mi_end = mi.mi_end2;\n\t}",
"\t// Count the word in the first language where it's found to be OK.\n\tif (count_word && mi.mi_result == SP_OK)\n\t{\n\t count_common_word(mi.mi_lp->lp_slang, ptr,\n\t\t\t\t\t\t (int)(mi.mi_end - ptr), 1);\n\t count_word = FALSE;\n\t}\n }",
" if (mi.mi_result != SP_OK)\n {\n\t// If we found a number skip over it. Allows for \"42nd\". Do flag\n\t// rare and local words, e.g., \"3GPP\".\n\tif (nrlen > 0)\n\t{\n\t if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)\n\t\treturn nrlen;\n\t}",
"\t// When we are at a non-word character there is no error, just\n\t// skip over the character (try looking for a word after it).\n\telse if (!spell_iswordp_nmw(ptr, wp))\n\t{\n\t if (capcol != NULL && wp->w_s->b_cap_prog != NULL)\n\t {\n\t\tregmatch_T\tregmatch;\n\t\tint\t\tr;",
"\t\t// Check for end of sentence.\n\t\tregmatch.regprog = wp->w_s->b_cap_prog;\n\t\tregmatch.rm_ic = FALSE;\n\t\tr = vim_regexec(®match, ptr, 0);\n\t\twp->w_s->b_cap_prog = regmatch.regprog;\n\t\tif (r)\n\t\t *capcol = (int)(regmatch.endp[0] - ptr);\n\t }",
"\t if (has_mbyte)\n\t\treturn (*mb_ptr2len)(ptr);\n\t return 1;\n\t}\n\telse if (mi.mi_end == ptr)\n\t // Always include at least one character. Required for when there\n\t // is a mixup in \"midword\".\n\t MB_PTR_ADV(mi.mi_end);\n\telse if (mi.mi_result == SP_BAD\n\t\t&& LANGP_ENTRY(wp->w_s->b_langp, 0)->lp_slang->sl_nobreak)\n\t{\n\t char_u\t*p, *fp;\n\t int\t\tsave_result = mi.mi_result;",
"\t // First language in 'spelllang' is NOBREAK. Find first position\n\t // at which any word would be valid.\n\t mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, 0);\n\t if (mi.mi_lp->lp_slang->sl_fidxs != NULL)\n\t {\n\t\tp = mi.mi_word;\n\t\tfp = mi.mi_fword;\n\t\tfor (;;)\n\t\t{\n\t\t MB_PTR_ADV(p);\n\t\t MB_PTR_ADV(fp);\n\t\t if (p >= mi.mi_end)\n\t\t\tbreak;\n\t\t mi.mi_compoff = (int)(fp - mi.mi_fword);\n\t\t find_word(&mi, FIND_COMPOUND);\n\t\t if (mi.mi_result != SP_BAD)\n\t\t {\n\t\t\tmi.mi_end = p;\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t\tmi.mi_result = save_result;\n\t }\n\t}",
"\tif (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)\n\t *attrp = HLF_SPB;\n\telse if (mi.mi_result == SP_RARE)\n\t *attrp = HLF_SPR;\n\telse\n\t *attrp = HLF_SPL;\n }",
" if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE))\n {\n\t// Report SpellCap only when the word isn't badly spelled.\n\t*attrp = HLF_SPC;\n\treturn wrongcaplen;\n }",
" return (int)(mi.mi_end - ptr);\n}",
"/*\n * Check if the word at \"mip->mi_word\" is in the tree.\n * When \"mode\" is FIND_FOLDWORD check in fold-case word tree.\n * When \"mode\" is FIND_KEEPWORD check in keep-case word tree.\n * When \"mode\" is FIND_PREFIX check for word after prefix in fold-case word\n * tree.\n *\n * For a match mip->mi_result is updated.\n */\n static void\nfind_word(matchinf_T *mip, int mode)\n{\n idx_T\tarridx = 0;\n int\t\tendlen[MAXWLEN]; // length at possible word endings\n idx_T\tendidx[MAXWLEN]; // possible word endings\n int\t\tendidxcnt = 0;\n int\t\tlen;\n int\t\twlen = 0;\n int\t\tflen;\n int\t\tc;\n char_u\t*ptr;\n idx_T\tlo, hi, m;\n char_u\t*s;\n char_u\t*p;\n int\t\tres = SP_BAD;\n slang_T\t*slang = mip->mi_lp->lp_slang;\n unsigned\tflags;\n char_u\t*byts;\n idx_T\t*idxs;\n int\t\tword_ends;\n int\t\tprefix_found;\n int\t\tnobreak_result;",
" if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND)\n {\n\t// Check for word with matching case in keep-case tree.\n\tptr = mip->mi_word;\n\tflen = 9999;\t\t // no case folding, always enough bytes\n\tbyts = slang->sl_kbyts;\n\tidxs = slang->sl_kidxs;",
"\tif (mode == FIND_KEEPCOMPOUND)\n\t // Skip over the previously found word(s).\n\t wlen += mip->mi_compoff;\n }\n else\n {\n\t// Check for case-folded in case-folded tree.\n\tptr = mip->mi_fword;\n\tflen = mip->mi_fwordlen; // available case-folded bytes\n\tbyts = slang->sl_fbyts;\n\tidxs = slang->sl_fidxs;",
"\tif (mode == FIND_PREFIX)\n\t{\n\t // Skip over the prefix.\n\t wlen = mip->mi_prefixlen;\n\t flen -= mip->mi_prefixlen;\n\t}\n\telse if (mode == FIND_COMPOUND)\n\t{\n\t // Skip over the previously found word(s).\n\t wlen = mip->mi_compoff;\n\t flen -= mip->mi_compoff;\n\t}",
" }",
" if (byts == NULL)\n\treturn;\t\t\t// array is empty",
" /*\n * Repeat advancing in the tree until:\n * - there is a byte that doesn't match,\n * - we reach the end of the tree,\n * - or we reach the end of the line.\n */\n for (;;)\n {\n\tif (flen <= 0 && *mip->mi_fend != NUL)\n\t flen = fold_more(mip);",
"\tlen = byts[arridx++];",
"\t// If the first possible byte is a zero the word could end here.\n\t// Remember this index, we first check for the longest word.\n\tif (byts[arridx] == 0)\n\t{\n\t if (endidxcnt == MAXWLEN)\n\t {\n\t\t// Must be a corrupted spell file.\n\t\temsg(_(e_format_error_in_spell_file));\n\t\treturn;\n\t }\n\t endlen[endidxcnt] = wlen;\n\t endidx[endidxcnt++] = arridx++;\n\t --len;",
"\t // Skip over the zeros, there can be several flag/region\n\t // combinations.\n\t while (len > 0 && byts[arridx] == 0)\n\t {\n\t\t++arridx;\n\t\t--len;\n\t }\n\t if (len == 0)\n\t\tbreak;\t // no children, word must end here\n\t}",
"\t// Stop looking at end of the line.\n\tif (ptr[wlen] == NUL)\n\t break;",
"\t// Perform a binary search in the list of accepted bytes.\n\tc = ptr[wlen];\n\tif (c == TAB)\t // <Tab> is handled like <Space>\n\t c = ' ';\n\tlo = arridx;\n\thi = arridx + len - 1;\n\twhile (lo < hi)\n\t{\n\t m = (lo + hi) / 2;\n\t if (byts[m] > c)\n\t\thi = m - 1;\n\t else if (byts[m] < c)\n\t\tlo = m + 1;\n\t else\n\t {\n\t\tlo = hi = m;\n\t\tbreak;\n\t }\n\t}",
"\t// Stop if there is no matching byte.\n\tif (hi < lo || byts[lo] != c)\n\t break;",
"\t// Continue at the child (if there is one).\n\tarridx = idxs[lo];\n\t++wlen;\n\t--flen;",
"\t// One space in the good word may stand for several spaces in the\n\t// checked word.\n\tif (c == ' ')\n\t{\n\t for (;;)\n\t {\n\t\tif (flen <= 0 && *mip->mi_fend != NUL)\n\t\t flen = fold_more(mip);\n\t\tif (ptr[wlen] != ' ' && ptr[wlen] != TAB)\n\t\t break;\n\t\t++wlen;\n\t\t--flen;\n\t }\n\t}\n }",
" /*\n * Verify that one of the possible endings is valid. Try the longest\n * first.\n */\n while (endidxcnt > 0)\n {\n\t--endidxcnt;\n\tarridx = endidx[endidxcnt];\n\twlen = endlen[endidxcnt];",
"\tif ((*mb_head_off)(ptr, ptr + wlen) > 0)\n\t continue;\t // not at first byte of character\n\tif (spell_iswordp(ptr + wlen, mip->mi_win))\n\t{\n\t if (slang->sl_compprog == NULL && !slang->sl_nobreak)\n\t\tcontinue;\t // next char is a word character\n\t word_ends = FALSE;\n\t}\n\telse\n\t word_ends = TRUE;\n\t// The prefix flag is before compound flags. Once a valid prefix flag\n\t// has been found we try compound flags.\n\tprefix_found = FALSE;",
"\tif (mode != FIND_KEEPWORD && has_mbyte)\n\t{\n\t // Compute byte length in original word, length may change\n\t // when folding case. This can be slow, take a shortcut when the\n\t // case-folded word is equal to the keep-case word.\n\t p = mip->mi_word;\n\t if (STRNCMP(ptr, p, wlen) != 0)\n\t {\n\t\tfor (s = ptr; s < ptr + wlen; MB_PTR_ADV(s))\n\t\t MB_PTR_ADV(p);\n\t\twlen = (int)(p - mip->mi_word);\n\t }\n\t}",
"\t// Check flags and region. For FIND_PREFIX check the condition and\n\t// prefix ID.\n\t// Repeat this if there are more flags/region alternatives until there\n\t// is a match.\n\tres = SP_BAD;\n\tfor (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0;\n\t\t\t\t\t\t\t --len, ++arridx)\n\t{\n\t flags = idxs[arridx];",
"\t // For the fold-case tree check that the case of the checked word\n\t // matches with what the word in the tree requires.\n\t // For keep-case tree the case is always right. For prefixes we\n\t // don't bother to check.\n\t if (mode == FIND_FOLDWORD)\n\t {\n\t\tif (mip->mi_cend != mip->mi_word + wlen)\n\t\t{\n\t\t // mi_capflags was set for a different word length, need\n\t\t // to do it again.\n\t\t mip->mi_cend = mip->mi_word + wlen;\n\t\t mip->mi_capflags = captype(mip->mi_word, mip->mi_cend);\n\t\t}",
"\t\tif (mip->mi_capflags == WF_KEEPCAP\n\t\t\t\t|| !spell_valid_case(mip->mi_capflags, flags))\n\t\t continue;\n\t }",
"\t // When mode is FIND_PREFIX the word must support the prefix:\n\t // check the prefix ID and the condition. Do that for the list at\n\t // mip->mi_prefarridx that find_prefix() filled.\n\t else if (mode == FIND_PREFIX && !prefix_found)\n\t {\n\t\tc = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx,\n\t\t\t\t flags,\n\t\t\t\t mip->mi_word + mip->mi_cprefixlen, slang,\n\t\t\t\t FALSE);\n\t\tif (c == 0)\n\t\t continue;",
"\t\t// Use the WF_RARE flag for a rare prefix.\n\t\tif (c & WF_RAREPFX)\n\t\t flags |= WF_RARE;\n\t\tprefix_found = TRUE;\n\t }",
"\t if (slang->sl_nobreak)\n\t {\n\t\tif ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND)\n\t\t\t&& (flags & WF_BANNED) == 0)\n\t\t{\n\t\t // NOBREAK: found a valid following word. That's all we\n\t\t // need to know, so return.\n\t\t mip->mi_result = SP_OK;\n\t\t break;\n\t\t}\n\t }",
"\t else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND\n\t\t\t\t\t\t\t\t|| !word_ends))\n\t {\n\t\t// If there is no compound flag or the word is shorter than\n\t\t// COMPOUNDMIN reject it quickly.\n\t\t// Makes you wonder why someone puts a compound flag on a word\n\t\t// that's too short... Myspell compatibility requires this\n\t\t// anyway.\n\t\tif (((unsigned)flags >> 24) == 0\n\t\t\t || wlen - mip->mi_compoff < slang->sl_compminlen)\n\t\t continue;\n\t\t// For multi-byte chars check character length against\n\t\t// COMPOUNDMIN.\n\t\tif (has_mbyte\n\t\t\t&& slang->sl_compminlen > 0\n\t\t\t&& mb_charlen_len(mip->mi_word + mip->mi_compoff,\n\t\t\t\twlen - mip->mi_compoff) < slang->sl_compminlen)\n\t\t\tcontinue;",
"\t\t// Limit the number of compound words to COMPOUNDWORDMAX if no\n\t\t// maximum for syllables is specified.\n\t\tif (!word_ends && mip->mi_complen + mip->mi_compextra + 2\n\t\t\t\t\t\t\t > slang->sl_compmax\n\t\t\t\t\t && slang->sl_compsylmax == MAXWLEN)\n\t\t continue;",
"\t\t// Don't allow compounding on a side where an affix was added,\n\t\t// unless COMPOUNDPERMITFLAG was used.\n\t\tif (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF))\n\t\t continue;\n\t\tif (!word_ends && (flags & WF_NOCOMPAFT))\n\t\t continue;",
"\t\t// Quickly check if compounding is possible with this flag.\n\t\tif (!byte_in_str(mip->mi_complen == 0\n\t\t\t\t\t? slang->sl_compstartflags\n\t\t\t\t\t: slang->sl_compallflags,\n\t\t\t\t\t ((unsigned)flags >> 24)))\n\t\t continue;",
"\t\t// If there is a match with a CHECKCOMPOUNDPATTERN rule\n\t\t// discard the compound word.\n\t\tif (match_checkcompoundpattern(ptr, wlen, &slang->sl_comppat))\n\t\t continue;",
"\t\tif (mode == FIND_COMPOUND)\n\t\t{\n\t\t int\t capflags;",
"\t\t // Need to check the caps type of the appended compound\n\t\t // word.\n\t\t if (has_mbyte && STRNCMP(ptr, mip->mi_word,\n\t\t\t\t\t\t\tmip->mi_compoff) != 0)\n\t\t {\n\t\t\t// case folding may have changed the length\n\t\t\tp = mip->mi_word;\n\t\t\tfor (s = ptr; s < ptr + mip->mi_compoff; MB_PTR_ADV(s))\n\t\t\t MB_PTR_ADV(p);\n\t\t }\n\t\t else\n\t\t\tp = mip->mi_word + mip->mi_compoff;\n\t\t capflags = captype(p, mip->mi_word + wlen);\n\t\t if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP\n\t\t\t\t\t\t && (flags & WF_FIXCAP) != 0))\n\t\t\tcontinue;",
"\t\t if (capflags != WF_ALLCAP)\n\t\t {\n\t\t\t// When the character before the word is a word\n\t\t\t// character we do not accept a Onecap word. We do\n\t\t\t// accept a no-caps word, even when the dictionary\n\t\t\t// word specifies ONECAP.\n\t\t\tMB_PTR_BACK(mip->mi_word, p);\n\t\t\tif (spell_iswordp_nmw(p, mip->mi_win)\n\t\t\t\t? capflags == WF_ONECAP\n\t\t\t\t: (flags & WF_ONECAP) != 0\n\t\t\t\t\t\t && capflags != WF_ONECAP)\n\t\t\t continue;\n\t\t }\n\t\t}",
"\t\t// If the word ends the sequence of compound flags of the\n\t\t// words must match with one of the COMPOUNDRULE items and\n\t\t// the number of syllables must not be too large.\n\t\tmip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24);\n\t\tmip->mi_compflags[mip->mi_complen + 1] = NUL;\n\t\tif (word_ends)\n\t\t{\n\t\t char_u\tfword[MAXWLEN];",
"\t\t if (slang->sl_compsylmax < MAXWLEN)\n\t\t {\n\t\t\t// \"fword\" is only needed for checking syllables.\n\t\t\tif (ptr == mip->mi_word)\n\t\t\t (void)spell_casefold(mip->mi_win,\n\t\t\t\t\t\t ptr, wlen, fword, MAXWLEN);\n\t\t\telse\n\t\t\t vim_strncpy(fword, ptr, endlen[endidxcnt]);\n\t\t }\n\t\t if (!can_compound(slang, fword, mip->mi_compflags))\n\t\t\tcontinue;\n\t\t}\n\t\telse if (slang->sl_comprules != NULL\n\t\t\t && !match_compoundrule(slang, mip->mi_compflags))\n\t\t // The compound flags collected so far do not match any\n\t\t // COMPOUNDRULE, discard the compounded word.\n\t\t continue;\n\t }",
"\t // Check NEEDCOMPOUND: can't use word without compounding.\n\t else if (flags & WF_NEEDCOMP)\n\t\tcontinue;",
"\t nobreak_result = SP_OK;",
"\t if (!word_ends)\n\t {\n\t\tint\tsave_result = mip->mi_result;\n\t\tchar_u\t*save_end = mip->mi_end;\n\t\tlangp_T\t*save_lp = mip->mi_lp;\n\t\tint\tlpi;",
"\t\t// Check that a valid word follows. If there is one and we\n\t\t// are compounding, it will set \"mi_result\", thus we are\n\t\t// always finished here. For NOBREAK we only check that a\n\t\t// valid word follows.\n\t\t// Recursive!\n\t\tif (slang->sl_nobreak)\n\t\t mip->mi_result = SP_BAD;",
"\t\t// Find following word in case-folded tree.\n\t\tmip->mi_compoff = endlen[endidxcnt];\n\t\tif (has_mbyte && mode == FIND_KEEPWORD)\n\t\t{\n\t\t // Compute byte length in case-folded word from \"wlen\":\n\t\t // byte length in keep-case word. Length may change when\n\t\t // folding case. This can be slow, take a shortcut when\n\t\t // the case-folded word is equal to the keep-case word.\n\t\t p = mip->mi_fword;\n\t\t if (STRNCMP(ptr, p, wlen) != 0)\n\t\t {\n\t\t\tfor (s = ptr; s < ptr + wlen; MB_PTR_ADV(s))\n\t\t\t MB_PTR_ADV(p);\n\t\t\tmip->mi_compoff = (int)(p - mip->mi_fword);\n\t\t }\n\t\t}\n#if 0 // Disabled, see below\n\t\tc = mip->mi_compoff;\n#endif\n\t\t++mip->mi_complen;\n\t\tif (flags & WF_COMPROOT)\n\t\t ++mip->mi_compextra;",
"\t\t// For NOBREAK we need to try all NOBREAK languages, at least\n\t\t// to find the \".add\" file(s).\n\t\tfor (lpi = 0; lpi < mip->mi_win->w_s->b_langp.ga_len; ++lpi)\n\t\t{\n\t\t if (slang->sl_nobreak)\n\t\t {\n\t\t\tmip->mi_lp = LANGP_ENTRY(mip->mi_win->w_s->b_langp, lpi);\n\t\t\tif (mip->mi_lp->lp_slang->sl_fidxs == NULL\n\t\t\t\t\t || !mip->mi_lp->lp_slang->sl_nobreak)\n\t\t\t continue;\n\t\t }",
"\t\t find_word(mip, FIND_COMPOUND);",
"\t\t // When NOBREAK any word that matches is OK. Otherwise we\n\t\t // need to find the longest match, thus try with keep-case\n\t\t // and prefix too.\n\t\t if (!slang->sl_nobreak || mip->mi_result == SP_BAD)\n\t\t {\n\t\t\t// Find following word in keep-case tree.\n\t\t\tmip->mi_compoff = wlen;\n\t\t\tfind_word(mip, FIND_KEEPCOMPOUND);",
"#if 0\t // Disabled, a prefix must not appear halfway a compound word,\n\t // unless the COMPOUNDPERMITFLAG is used and then it can't be a\n\t // postponed prefix.\n\t\t\tif (!slang->sl_nobreak || mip->mi_result == SP_BAD)\n\t\t\t{\n\t\t\t // Check for following word with prefix.\n\t\t\t mip->mi_compoff = c;\n\t\t\t find_prefix(mip, FIND_COMPOUND);\n\t\t\t}\n#endif\n\t\t }",
"\t\t if (!slang->sl_nobreak)\n\t\t\tbreak;\n\t\t}\n\t\t--mip->mi_complen;\n\t\tif (flags & WF_COMPROOT)\n\t\t --mip->mi_compextra;\n\t\tmip->mi_lp = save_lp;",
"\t\tif (slang->sl_nobreak)\n\t\t{\n\t\t nobreak_result = mip->mi_result;\n\t\t mip->mi_result = save_result;\n\t\t mip->mi_end = save_end;\n\t\t}\n\t\telse\n\t\t{\n\t\t if (mip->mi_result == SP_OK)\n\t\t\tbreak;\n\t\t continue;\n\t\t}\n\t }",
"\t if (flags & WF_BANNED)\n\t\tres = SP_BANNED;\n\t else if (flags & WF_REGION)\n\t {\n\t\t// Check region.\n\t\tif ((mip->mi_lp->lp_region & (flags >> 16)) != 0)\n\t\t res = SP_OK;\n\t\telse\n\t\t res = SP_LOCAL;\n\t }\n\t else if (flags & WF_RARE)\n\t\tres = SP_RARE;\n\t else\n\t\tres = SP_OK;",
"\t // Always use the longest match and the best result. For NOBREAK\n\t // we separately keep the longest match without a following good\n\t // word as a fall-back.\n\t if (nobreak_result == SP_BAD)\n\t {\n\t\tif (mip->mi_result2 > res)\n\t\t{\n\t\t mip->mi_result2 = res;\n\t\t mip->mi_end2 = mip->mi_word + wlen;\n\t\t}\n\t\telse if (mip->mi_result2 == res\n\t\t\t\t\t&& mip->mi_end2 < mip->mi_word + wlen)\n\t\t mip->mi_end2 = mip->mi_word + wlen;\n\t }\n\t else if (mip->mi_result > res)\n\t {\n\t\tmip->mi_result = res;\n\t\tmip->mi_end = mip->mi_word + wlen;\n\t }\n\t else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen)\n\t\tmip->mi_end = mip->mi_word + wlen;",
"\t if (mip->mi_result == SP_OK)\n\t\tbreak;\n\t}",
"\tif (mip->mi_result == SP_OK)\n\t break;\n }\n}",
"/*\n * Return TRUE if there is a match between the word ptr[wlen] and\n * CHECKCOMPOUNDPATTERN rules, assuming that we will concatenate with another\n * word.\n * A match means that the first part of CHECKCOMPOUNDPATTERN matches at the\n * end of ptr[wlen] and the second part matches after it.\n */\n int\nmatch_checkcompoundpattern(\n char_u\t*ptr,\n int\t\twlen,\n garray_T\t*gap) // &sl_comppat\n{\n int\t\ti;\n char_u\t*p;\n int\t\tlen;",
" for (i = 0; i + 1 < gap->ga_len; i += 2)\n {\n\tp = ((char_u **)gap->ga_data)[i + 1];\n\tif (STRNCMP(ptr + wlen, p, STRLEN(p)) == 0)\n\t{\n\t // Second part matches at start of following compound word, now\n\t // check if first part matches at end of previous word.\n\t p = ((char_u **)gap->ga_data)[i];\n\t len = (int)STRLEN(p);\n\t if (len <= wlen && STRNCMP(ptr + wlen - len, p, len) == 0)\n\t\treturn TRUE;\n\t}\n }\n return FALSE;\n}",
"/*\n * Return TRUE if \"flags\" is a valid sequence of compound flags and \"word\"\n * does not have too many syllables.\n */\n int\ncan_compound(slang_T *slang, char_u *word, char_u *flags)\n{\n char_u\tuflags[MAXWLEN * 2];\n int\t\ti;\n char_u\t*p;",
" if (slang->sl_compprog == NULL)\n\treturn FALSE;\n if (enc_utf8)\n {\n\t// Need to convert the single byte flags to utf8 characters.\n\tp = uflags;\n\tfor (i = 0; flags[i] != NUL; ++i)\n\t p += utf_char2bytes(flags[i], p);\n\t*p = NUL;\n\tp = uflags;\n }\n else\n\tp = flags;\n if (!vim_regexec_prog(&slang->sl_compprog, FALSE, p, 0))\n\treturn FALSE;",
" // Count the number of syllables. This may be slow, do it last. If there\n // are too many syllables AND the number of compound words is above\n // COMPOUNDWORDMAX then compounding is not allowed.\n if (slang->sl_compsylmax < MAXWLEN\n\t\t && count_syllables(slang, word) > slang->sl_compsylmax)\n\treturn (int)STRLEN(flags) < slang->sl_compmax;\n return TRUE;\n}",
"/*\n * Return TRUE if the compound flags in compflags[] match the start of any\n * compound rule. This is used to stop trying a compound if the flags\n * collected so far can't possibly match any compound rule.\n * Caller must check that slang->sl_comprules is not NULL.\n */\n int\nmatch_compoundrule(slang_T *slang, char_u *compflags)\n{\n char_u\t*p;\n int\t\ti;\n int\t\tc;",
" // loop over all the COMPOUNDRULE entries\n for (p = slang->sl_comprules; *p != NUL; ++p)\n {\n\t// loop over the flags in the compound word we have made, match\n\t// them against the current rule entry\n\tfor (i = 0; ; ++i)\n\t{\n\t c = compflags[i];\n\t if (c == NUL)\n\t\t// found a rule that matches for the flags we have so far\n\t\treturn TRUE;\n\t if (*p == '/' || *p == NUL)\n\t\tbreak; // end of rule, it's too short\n\t if (*p == '[')\n\t {\n\t\tint match = FALSE;",
"\t\t// compare against all the flags in []\n\t\t++p;\n\t\twhile (*p != ']' && *p != NUL)\n\t\t if (*p++ == c)\n\t\t\tmatch = TRUE;\n\t\tif (!match)\n\t\t break; // none matches\n\t }\n\t else if (*p != c)\n\t\tbreak; // flag of word doesn't match flag in pattern\n\t ++p;\n\t}",
"\t// Skip to the next \"/\", where the next pattern starts.\n\tp = vim_strchr(p, '/');\n\tif (p == NULL)\n\t break;\n }",
" // Checked all the rules and none of them match the flags, so there\n // can't possibly be a compound starting with these flags.\n return FALSE;\n}",
"/*\n * Return non-zero if the prefix indicated by \"arridx\" matches with the prefix\n * ID in \"flags\" for the word \"word\".\n * The WF_RAREPFX flag is included in the return value for a rare prefix.\n */\n int\nvalid_word_prefix(\n int\t\ttotprefcnt,\t// nr of prefix IDs\n int\t\tarridx,\t\t// idx in sl_pidxs[]\n int\t\tflags,\n char_u\t*word,\n slang_T\t*slang,\n int\t\tcond_req)\t// only use prefixes with a condition\n{\n int\t\tprefcnt;\n int\t\tpidx;\n regprog_T\t**rp;\n int\t\tprefid;",
" prefid = (unsigned)flags >> 24;\n for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt)\n {\n\tpidx = slang->sl_pidxs[arridx + prefcnt];",
"\t// Check the prefix ID.\n\tif (prefid != (pidx & 0xff))\n\t continue;",
"\t// Check if the prefix doesn't combine and the word already has a\n\t// suffix.\n\tif ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC))\n\t continue;",
"\t// Check the condition, if there is one. The condition index is\n\t// stored in the two bytes above the prefix ID byte.\n\trp = &slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff];\n\tif (*rp != NULL)\n\t{\n\t if (!vim_regexec_prog(rp, FALSE, word, 0))\n\t\tcontinue;\n\t}\n\telse if (cond_req)\n\t continue;",
"\t// It's a match! Return the WF_ flags.\n\treturn pidx;\n }\n return 0;\n}",
"/*\n * Check if the word at \"mip->mi_word\" has a matching prefix.\n * If it does, then check the following word.\n *\n * If \"mode\" is \"FIND_COMPOUND\" then do the same after another word, find a\n * prefix in a compound word.\n *\n * For a match mip->mi_result is updated.\n */\n static void\nfind_prefix(matchinf_T *mip, int mode)\n{\n idx_T\tarridx = 0;\n int\t\tlen;\n int\t\twlen = 0;\n int\t\tflen;\n int\t\tc;\n char_u\t*ptr;\n idx_T\tlo, hi, m;\n slang_T\t*slang = mip->mi_lp->lp_slang;\n char_u\t*byts;\n idx_T\t*idxs;",
" byts = slang->sl_pbyts;\n if (byts == NULL)\n\treturn;\t\t\t// array is empty",
" // We use the case-folded word here, since prefixes are always\n // case-folded.\n ptr = mip->mi_fword;\n flen = mip->mi_fwordlen; // available case-folded bytes\n if (mode == FIND_COMPOUND)\n {\n\t// Skip over the previously found word(s).\n\tptr += mip->mi_compoff;\n\tflen -= mip->mi_compoff;\n }\n idxs = slang->sl_pidxs;",
" /*\n * Repeat advancing in the tree until:\n * - there is a byte that doesn't match,\n * - we reach the end of the tree,\n * - or we reach the end of the line.\n */\n for (;;)\n {\n\tif (flen == 0 && *mip->mi_fend != NUL)\n\t flen = fold_more(mip);",
"\tlen = byts[arridx++];",
"\t// If the first possible byte is a zero the prefix could end here.\n\t// Check if the following word matches and supports the prefix.\n\tif (byts[arridx] == 0)\n\t{\n\t // There can be several prefixes with different conditions. We\n\t // try them all, since we don't know which one will give the\n\t // longest match. The word is the same each time, pass the list\n\t // of possible prefixes to find_word().\n\t mip->mi_prefarridx = arridx;\n\t mip->mi_prefcnt = len;\n\t while (len > 0 && byts[arridx] == 0)\n\t {\n\t\t++arridx;\n\t\t--len;\n\t }\n\t mip->mi_prefcnt -= len;",
"\t // Find the word that comes after the prefix.\n\t mip->mi_prefixlen = wlen;\n\t if (mode == FIND_COMPOUND)\n\t\t// Skip over the previously found word(s).\n\t\tmip->mi_prefixlen += mip->mi_compoff;",
"\t if (has_mbyte)\n\t {\n\t\t// Case-folded length may differ from original length.\n\t\tmip->mi_cprefixlen = nofold_len(mip->mi_fword,\n\t\t\t\t\t mip->mi_prefixlen, mip->mi_word);\n\t }\n\t else\n\t\tmip->mi_cprefixlen = mip->mi_prefixlen;\n\t find_word(mip, FIND_PREFIX);",
"\n\t if (len == 0)\n\t\tbreak;\t // no children, word must end here\n\t}",
"\t// Stop looking at end of the line.\n\tif (ptr[wlen] == NUL)\n\t break;",
"\t// Perform a binary search in the list of accepted bytes.\n\tc = ptr[wlen];\n\tlo = arridx;\n\thi = arridx + len - 1;\n\twhile (lo < hi)\n\t{\n\t m = (lo + hi) / 2;\n\t if (byts[m] > c)\n\t\thi = m - 1;\n\t else if (byts[m] < c)\n\t\tlo = m + 1;\n\t else\n\t {\n\t\tlo = hi = m;\n\t\tbreak;\n\t }\n\t}",
"\t// Stop if there is no matching byte.\n\tif (hi < lo || byts[lo] != c)\n\t break;",
"\t// Continue at the child (if there is one).\n\tarridx = idxs[lo];\n\t++wlen;\n\t--flen;\n }\n}",
"/*\n * Need to fold at least one more character. Do until next non-word character\n * for efficiency. Include the non-word character too.\n * Return the length of the folded chars in bytes.\n */\n static int\nfold_more(matchinf_T *mip)\n{\n int\t\tflen;\n char_u\t*p;",
" p = mip->mi_fend;\n do\n\tMB_PTR_ADV(mip->mi_fend);\n while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_win));",
" // Include the non-word character so that we can check for the word end.\n if (*mip->mi_fend != NUL)\n\tMB_PTR_ADV(mip->mi_fend);",
" (void)spell_casefold(mip->mi_win, p, (int)(mip->mi_fend - p),\n\t\t\t mip->mi_fword + mip->mi_fwordlen,\n\t\t\t MAXWLEN - mip->mi_fwordlen);\n flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen);\n mip->mi_fwordlen += flen;\n return flen;\n}",
"/*\n * Check case flags for a word. Return TRUE if the word has the requested\n * case.\n */\n int\nspell_valid_case(\n int\t wordflags,\t // flags for the checked word.\n int\t treeflags)\t // flags for the word in the spell tree\n{\n return ((wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0)\n\t || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0\n\t\t&& ((treeflags & WF_ONECAP) == 0\n\t\t\t\t\t || (wordflags & WF_ONECAP) != 0)));\n}",
"/*\n * Return TRUE if spell checking is not enabled.\n */\n static int\nno_spell_checking(win_T *wp)\n{\n if (!wp->w_p_spell || *wp->w_s->b_p_spl == NUL\n\t\t\t\t\t || wp->w_s->b_langp.ga_len == 0)\n {\n\temsg(_(e_spell_checking_is_not_possible));\n\treturn TRUE;\n }\n return FALSE;\n}",
"/*\n * Move to next spell error.\n * \"curline\" is FALSE for \"[s\", \"]s\", \"[S\" and \"]S\".\n * \"curline\" is TRUE to find word under/after cursor in the same line.\n * For Insert mode completion \"dir\" is BACKWARD and \"curline\" is TRUE: move\n * to after badly spelled word before the cursor.\n * Return 0 if not found, length of the badly spelled word otherwise.\n */\n int\nspell_move_to(\n win_T\t*wp,\n int\t\tdir,\t\t// FORWARD or BACKWARD\n int\t\tallwords,\t// TRUE for \"[s\"/\"]s\", FALSE for \"[S\"/\"]S\"\n int\t\tcurline,\n hlf_T\t*attrp)\t\t// return: attributes of bad word or NULL\n\t\t\t\t// (only when \"dir\" is FORWARD)\n{\n linenr_T\tlnum;\n pos_T\tfound_pos;\n int\t\tfound_len = 0;\n char_u\t*line;\n char_u\t*p;\n char_u\t*endp;",
" hlf_T\tattr = 0;",
" int\t\tlen;\n#ifdef FEAT_SYN_HL\n int\t\thas_syntax = syntax_present(wp);\n#endif\n int\t\tcol;\n int\t\tcan_spell;\n char_u\t*buf = NULL;\n int\t\tbuflen = 0;\n int\t\tskip = 0;\n int\t\tcapcol = -1;\n int\t\tfound_one = FALSE;\n int\t\twrapped = FALSE;",
" if (no_spell_checking(wp))\n\treturn 0;",
" /*\n * Start looking for bad word at the start of the line, because we can't\n * start halfway a word, we don't know where it starts or ends.\n *\n * When searching backwards, we continue in the line to find the last\n * bad word (in the cursor line: before the cursor).\n *\n * We concatenate the start of the next line, so that wrapped words work\n * (e.g. \"et<line-break>cetera\"). Doesn't work when searching backwards\n * though...\n */\n lnum = wp->w_cursor.lnum;\n CLEAR_POS(&found_pos);",
" while (!got_int)\n {",
"\tint empty_line;\n",
"\tline = ml_get_buf(wp->w_buffer, lnum, FALSE);",
"\tlen = (int)STRLEN(line);\n\tif (buflen < len + MAXWLEN + 2)\n\t{\n\t vim_free(buf);\n\t buflen = len + MAXWLEN + 2;\n\t buf = alloc(buflen);\n\t if (buf == NULL)\n\t\tbreak;\n\t}",
"\t// In first line check first word for Capital.\n\tif (lnum == 1)\n\t capcol = 0;",
"\t// For checking first word with a capital skip white space.\n\tif (capcol == 0)\n\t capcol = getwhitecols(line);\n\telse if (curline && wp == curwin)\n\t{\n\t // For spellbadword(): check if first word needs a capital.\n\t col = getwhitecols(line);\n\t if (check_need_cap(lnum, col))\n\t\tcapcol = col;",
"\t // Need to get the line again, may have looked at the previous\n\t // one.\n\t line = ml_get_buf(wp->w_buffer, lnum, FALSE);\n\t}",
"\t// Copy the line into \"buf\" and append the start of the next line if",
"\t// possible. Note: this ml_get_buf() may make \"line\" invalid, check\n\t// for empty line first.\n\tempty_line = *skipwhite(line) == NUL;",
"\tSTRCPY(buf, line);\n\tif (lnum < wp->w_buffer->b_ml.ml_line_count)\n\t spell_cat_line(buf + STRLEN(buf),\n\t\t\t ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN);",
"\tp = buf + skip;\n\tendp = buf + len;\n\twhile (p < endp)\n\t{\n\t // When searching backward don't search after the cursor. Unless\n\t // we wrapped around the end of the buffer.\n\t if (dir == BACKWARD\n\t\t && lnum == wp->w_cursor.lnum\n\t\t && !wrapped\n\t\t && (colnr_T)(p - buf) >= wp->w_cursor.col)\n\t\tbreak;",
"\t // start of word\n\t attr = HLF_COUNT;\n\t len = spell_check(wp, p, &attr, &capcol, FALSE);",
"\t if (attr != HLF_COUNT)\n\t {\n\t\t// We found a bad word. Check the attribute.\n\t\tif (allwords || attr == HLF_SPB)\n\t\t{\n\t\t // When searching forward only accept a bad word after\n\t\t // the cursor.\n\t\t if (dir == BACKWARD\n\t\t\t || lnum != wp->w_cursor.lnum\n\t\t\t || (wrapped\n\t\t\t\t|| (colnr_T)(curline ? p - buf + len\n\t\t\t\t\t\t : p - buf)\n\t\t\t\t\t\t > wp->w_cursor.col))\n\t\t {\n#ifdef FEAT_SYN_HL\n\t\t\tif (has_syntax)\n\t\t\t{\n\t\t\t col = (int)(p - buf);\n\t\t\t (void)syn_get_id(wp, lnum, (colnr_T)col,\n\t\t\t\t\t\t FALSE, &can_spell, FALSE);\n\t\t\t if (!can_spell)\n\t\t\t\tattr = HLF_COUNT;\n\t\t\t}\n\t\t\telse\n#endif\n\t\t\t can_spell = TRUE;",
"\t\t\tif (can_spell)\n\t\t\t{\n\t\t\t found_one = TRUE;\n\t\t\t found_pos.lnum = lnum;\n\t\t\t found_pos.col = (int)(p - buf);\n\t\t\t found_pos.coladd = 0;\n\t\t\t if (dir == FORWARD)\n\t\t\t {\n\t\t\t\t// No need to search further.\n\t\t\t\twp->w_cursor = found_pos;\n\t\t\t\tvim_free(buf);\n\t\t\t\tif (attrp != NULL)\n\t\t\t\t *attrp = attr;\n\t\t\t\treturn len;\n\t\t\t }\n\t\t\t else if (curline)\n\t\t\t\t// Insert mode completion: put cursor after\n\t\t\t\t// the bad word.\n\t\t\t\tfound_pos.col += len;\n\t\t\t found_len = len;\n\t\t\t}\n\t\t }\n\t\t else\n\t\t\tfound_one = TRUE;\n\t\t}\n\t }",
"\t // advance to character after the word\n\t p += len;\n\t capcol -= len;\n\t}",
"\tif (dir == BACKWARD && found_pos.lnum != 0)\n\t{\n\t // Use the last match in the line (before the cursor).\n\t wp->w_cursor = found_pos;\n\t vim_free(buf);\n\t return found_len;\n\t}",
"\tif (curline)\n\t break;\t// only check cursor line",
"\t// If we are back at the starting line and searched it again there\n\t// is no match, give up.\n\tif (lnum == wp->w_cursor.lnum && wrapped)\n\t break;",
"\t// Advance to next line.\n\tif (dir == BACKWARD)\n\t{\n\t if (lnum > 1)\n\t\t--lnum;\n\t else if (!p_ws)\n\t\tbreak;\t // at first line and 'nowrapscan'\n\t else\n\t {\n\t\t// Wrap around to the end of the buffer. May search the\n\t\t// starting line again and accept the last match.\n\t\tlnum = wp->w_buffer->b_ml.ml_line_count;\n\t\twrapped = TRUE;\n\t\tif (!shortmess(SHM_SEARCH))\n\t\t give_warning((char_u *)_(top_bot_msg), TRUE);\n\t }\n\t capcol = -1;\n\t}\n\telse\n\t{\n\t if (lnum < wp->w_buffer->b_ml.ml_line_count)\n\t\t++lnum;\n\t else if (!p_ws)\n\t\tbreak;\t // at first line and 'nowrapscan'\n\t else\n\t {\n\t\t// Wrap around to the start of the buffer. May search the\n\t\t// starting line again and accept the first match.\n\t\tlnum = 1;\n\t\twrapped = TRUE;\n\t\tif (!shortmess(SHM_SEARCH))\n\t\t give_warning((char_u *)_(bot_top_msg), TRUE);\n\t }",
"\t // If we are back at the starting line and there is no match then\n\t // give up.\n\t if (lnum == wp->w_cursor.lnum && !found_one)\n\t\tbreak;",
"\t // Skip the characters at the start of the next line that were\n\t // included in a match crossing line boundaries.\n\t if (attr == HLF_COUNT)\n\t\tskip = (int)(p - endp);\n\t else\n\t\tskip = 0;",
"\t // Capcol skips over the inserted space.\n\t --capcol;",
"\t // But after empty line check first word in next line",
"\t if (empty_line)",
"\t\tcapcol = 0;\n\t}",
"\tline_breakcheck();\n }",
" vim_free(buf);\n return 0;\n}",
"/*\n * For spell checking: concatenate the start of the following line \"line\" into\n * \"buf\", blanking-out special characters. Copy less than \"maxlen\" bytes.\n * Keep the blanks at the start of the next line, this is used in win_line()\n * to skip those bytes if the word was OK.\n */\n void\nspell_cat_line(char_u *buf, char_u *line, int maxlen)\n{\n char_u\t*p;\n int\t\tn;",
" p = skipwhite(line);\n while (vim_strchr((char_u *)\"*#/\\\"\\t\", *p) != NULL)\n\tp = skipwhite(p + 1);",
" if (*p != NUL)\n {\n\t// Only worth concatenating if there is something else than spaces to\n\t// concatenate.\n\tn = (int)(p - line) + 1;\n\tif (n < maxlen - 1)\n\t{\n\t vim_memset(buf, ' ', n);\n\t vim_strncpy(buf + n, p, maxlen - 1 - n);\n\t}\n }\n}",
"/*\n * Structure used for the cookie argument of do_in_runtimepath().\n */\ntypedef struct spelload_S\n{\n char_u sl_lang[MAXWLEN + 1];\t// language name\n slang_T *sl_slang;\t\t\t// resulting slang_T struct\n int\t sl_nobreak;\t\t\t// NOBREAK language found\n} spelload_T;",
"/*\n * Load word list(s) for \"lang\" from Vim spell file(s).\n * \"lang\" must be the language without the region: e.g., \"en\".\n */\n static void\nspell_load_lang(char_u *lang)\n{\n char_u\tfname_enc[85];\n int\t\tr;\n spelload_T\tsl;\n int\t\tround;",
" // Copy the language name to pass it to spell_load_cb() as a cookie.\n // It's truncated when an error is detected.\n STRCPY(sl.sl_lang, lang);\n sl.sl_slang = NULL;\n sl.sl_nobreak = FALSE;",
" // We may retry when no spell file is found for the language, an\n // autocommand may load it then.\n for (round = 1; round <= 2; ++round)\n {\n\t/*\n\t * Find the first spell file for \"lang\" in 'runtimepath' and load it.\n\t */\n\tvim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,\n#ifdef VMS\n\t\t\t\t\t\"spell/%s_%s.spl\",\n#else\n\t\t\t\t\t\"spell/%s.%s.spl\",\n#endif\n\t\t\t\t\t\t\t lang, spell_enc());\n\tr = do_in_runtimepath(fname_enc, 0, spell_load_cb, &sl);",
"\tif (r == FAIL && *sl.sl_lang != NUL)\n\t{\n\t // Try loading the ASCII version.\n\t vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,\n#ifdef VMS\n\t\t\t\t\t\t \"spell/%s_ascii.spl\",\n#else\n\t\t\t\t\t\t \"spell/%s.ascii.spl\",\n#endif\n\t\t\t\t\t\t\t\t\tlang);\n\t r = do_in_runtimepath(fname_enc, 0, spell_load_cb, &sl);",
"\t if (r == FAIL && *sl.sl_lang != NUL && round == 1\n\t\t && apply_autocmds(EVENT_SPELLFILEMISSING, lang,\n\t\t\t\t\t curbuf->b_fname, FALSE, curbuf))\n\t\tcontinue;\n\t break;\n\t}\n\tbreak;\n }",
" if (r == FAIL)\n {\n\tsmsg(\n#ifdef VMS\n\t_(\"Warning: Cannot find word list \\\"%s_%s.spl\\\" or \\\"%s_ascii.spl\\\"\"),\n#else\n\t_(\"Warning: Cannot find word list \\\"%s.%s.spl\\\" or \\\"%s.ascii.spl\\\"\"),\n#endif\n\t\t\t\t\t\t lang, spell_enc(), lang);\n }\n else if (sl.sl_slang != NULL)\n {\n\t// At least one file was loaded, now load ALL the additions.\n\tSTRCPY(fname_enc + STRLEN(fname_enc) - 3, \"add.spl\");\n\tdo_in_runtimepath(fname_enc, DIP_ALL, spell_load_cb, &sl);\n }\n}",
"/*\n * Return the encoding used for spell checking: Use 'encoding', except that we\n * use \"latin1\" for \"latin9\". And limit to 60 characters (just in case).\n */\n char_u *\nspell_enc(void)\n{",
" if (STRLEN(p_enc) < 60 && STRCMP(p_enc, \"iso-8859-15\") != 0)\n\treturn p_enc;\n return (char_u *)\"latin1\";\n}",
"/*\n * Get the name of the .spl file for the internal wordlist into\n * \"fname[MAXPATHL]\".\n */\n static void\nint_wordlist_spl(char_u *fname)\n{\n vim_snprintf((char *)fname, MAXPATHL, SPL_FNAME_TMPL,\n\t\t\t\t\t\t int_wordlist, spell_enc());\n}",
"/*\n * Allocate a new slang_T for language \"lang\". \"lang\" can be NULL.\n * Caller must fill \"sl_next\".\n */\n slang_T *\nslang_alloc(char_u *lang)\n{\n slang_T *lp;",
" lp = ALLOC_CLEAR_ONE(slang_T);\n if (lp != NULL)\n {\n\tif (lang != NULL)\n\t lp->sl_name = vim_strsave(lang);\n\tga_init2(&lp->sl_rep, sizeof(fromto_T), 10);\n\tga_init2(&lp->sl_repsal, sizeof(fromto_T), 10);\n\tlp->sl_compmax = MAXWLEN;\n\tlp->sl_compsylmax = MAXWLEN;\n\thash_init(&lp->sl_wordcount);\n }",
" return lp;\n}",
"/*\n * Free the contents of an slang_T and the structure itself.\n */\n void\nslang_free(slang_T *lp)\n{\n vim_free(lp->sl_name);\n vim_free(lp->sl_fname);\n slang_clear(lp);\n vim_free(lp);\n}",
"/*\n * Clear an slang_T so that the file can be reloaded.\n */\n void\nslang_clear(slang_T *lp)\n{\n garray_T\t*gap;\n fromto_T\t*ftp;\n salitem_T\t*smp;\n int\t\ti;\n int\t\tround;",
" VIM_CLEAR(lp->sl_fbyts);\n VIM_CLEAR(lp->sl_kbyts);\n VIM_CLEAR(lp->sl_pbyts);",
" VIM_CLEAR(lp->sl_fidxs);\n VIM_CLEAR(lp->sl_kidxs);\n VIM_CLEAR(lp->sl_pidxs);",
" for (round = 1; round <= 2; ++round)\n {\n\tgap = round == 1 ? &lp->sl_rep : &lp->sl_repsal;\n\twhile (gap->ga_len > 0)\n\t{\n\t ftp = &((fromto_T *)gap->ga_data)[--gap->ga_len];\n\t vim_free(ftp->ft_from);\n\t vim_free(ftp->ft_to);\n\t}\n\tga_clear(gap);\n }",
" gap = &lp->sl_sal;\n if (lp->sl_sofo)\n {\n\t// \"ga_len\" is set to 1 without adding an item for latin1\n\tif (gap->ga_data != NULL)\n\t // SOFOFROM and SOFOTO items: free lists of wide characters.\n\t for (i = 0; i < gap->ga_len; ++i)\n\t\tvim_free(((int **)gap->ga_data)[i]);\n }\n else\n\t// SAL items: free salitem_T items\n\twhile (gap->ga_len > 0)\n\t{\n\t smp = &((salitem_T *)gap->ga_data)[--gap->ga_len];\n\t vim_free(smp->sm_lead);\n\t // Don't free sm_oneof and sm_rules, they point into sm_lead.\n\t vim_free(smp->sm_to);\n\t vim_free(smp->sm_lead_w);\n\t vim_free(smp->sm_oneof_w);\n\t vim_free(smp->sm_to_w);\n\t}\n ga_clear(gap);",
" for (i = 0; i < lp->sl_prefixcnt; ++i)\n\tvim_regfree(lp->sl_prefprog[i]);\n lp->sl_prefixcnt = 0;\n VIM_CLEAR(lp->sl_prefprog);",
" VIM_CLEAR(lp->sl_info);",
" VIM_CLEAR(lp->sl_midword);",
" vim_regfree(lp->sl_compprog);\n lp->sl_compprog = NULL;\n VIM_CLEAR(lp->sl_comprules);\n VIM_CLEAR(lp->sl_compstartflags);\n VIM_CLEAR(lp->sl_compallflags);",
" VIM_CLEAR(lp->sl_syllable);\n ga_clear(&lp->sl_syl_items);",
" ga_clear_strings(&lp->sl_comppat);",
" hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF);\n hash_init(&lp->sl_wordcount);",
" hash_clear_all(&lp->sl_map_hash, 0);",
" // Clear info from .sug file.\n slang_clear_sug(lp);",
" lp->sl_compmax = MAXWLEN;\n lp->sl_compminlen = 0;\n lp->sl_compsylmax = MAXWLEN;\n lp->sl_regions[0] = NUL;\n}",
"/*\n * Clear the info from the .sug file in \"lp\".\n */\n void\nslang_clear_sug(slang_T *lp)\n{\n VIM_CLEAR(lp->sl_sbyts);\n VIM_CLEAR(lp->sl_sidxs);\n close_spellbuf(lp->sl_sugbuf);\n lp->sl_sugbuf = NULL;\n lp->sl_sugloaded = FALSE;\n lp->sl_sugtime = 0;\n}",
"/*\n * Load one spell file and store the info into a slang_T.\n * Invoked through do_in_runtimepath().\n */\n static void\nspell_load_cb(char_u *fname, void *cookie)\n{\n spelload_T\t*slp = (spelload_T *)cookie;\n slang_T\t*slang;",
" slang = spell_load_file(fname, slp->sl_lang, NULL, FALSE);\n if (slang != NULL)\n {\n\t// When a previously loaded file has NOBREAK also use it for the\n\t// \".add\" files.\n\tif (slp->sl_nobreak && slang->sl_add)\n\t slang->sl_nobreak = TRUE;\n\telse if (slang->sl_nobreak)\n\t slp->sl_nobreak = TRUE;",
"\tslp->sl_slang = slang;\n }\n}",
"\n/*\n * Add a word to the hashtable of common words.\n * If it's already there then the counter is increased.\n */\n void\ncount_common_word(\n slang_T\t*lp,\n char_u\t*word,\n int\t\tlen,\t // word length, -1 for up to NUL\n int\t\tcount)\t // 1 to count once, 10 to init\n{\n hash_T\thash;\n hashitem_T\t*hi;\n wordcount_T\t*wc;\n char_u\tbuf[MAXWLEN];\n char_u\t*p;",
" if (len == -1)\n\tp = word;\n else if (len >= MAXWLEN)\n\treturn;\n else\n {\n\tvim_strncpy(buf, word, len);\n\tp = buf;\n }",
" hash = hash_hash(p);\n hi = hash_lookup(&lp->sl_wordcount, p, hash);\n if (HASHITEM_EMPTY(hi))\n {\n\twc = alloc(sizeof(wordcount_T) + STRLEN(p));\n\tif (wc == NULL)\n\t return;\n\tSTRCPY(wc->wc_word, p);\n\twc->wc_count = count;\n\thash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash);\n }\n else\n {\n\twc = HI2WC(hi);\n\tif ((wc->wc_count += count) < (unsigned)count)\t// check for overflow\n\t wc->wc_count = MAXWORDCOUNT;\n }\n}",
"/*\n * Return TRUE if byte \"n\" appears in \"str\".\n * Like strchr() but independent of locale.\n */\n int\nbyte_in_str(char_u *str, int n)\n{\n char_u\t*p;",
" for (p = str; *p != NUL; ++p)\n\tif (*p == n)\n\t return TRUE;\n return FALSE;\n}",
"#define SY_MAXLEN 30\ntypedef struct syl_item_S\n{\n char_u\tsy_chars[SY_MAXLEN];\t // the sequence of chars\n int\t\tsy_len;\n} syl_item_T;",
"/*\n * Truncate \"slang->sl_syllable\" at the first slash and put the following items\n * in \"slang->sl_syl_items\".\n */\n int\ninit_syl_tab(slang_T *slang)\n{\n char_u\t*p;\n char_u\t*s;\n int\t\tl;\n syl_item_T\t*syl;",
" ga_init2(&slang->sl_syl_items, sizeof(syl_item_T), 4);\n p = vim_strchr(slang->sl_syllable, '/');\n while (p != NULL)\n {\n\t*p++ = NUL;\n\tif (*p == NUL)\t // trailing slash\n\t break;\n\ts = p;\n\tp = vim_strchr(p, '/');\n\tif (p == NULL)\n\t l = (int)STRLEN(s);\n\telse\n\t l = (int)(p - s);\n\tif (l >= SY_MAXLEN)\n\t return SP_FORMERROR;\n\tif (ga_grow(&slang->sl_syl_items, 1) == FAIL)\n\t return SP_OTHERERROR;\n\tsyl = ((syl_item_T *)slang->sl_syl_items.ga_data)\n\t\t\t\t\t + slang->sl_syl_items.ga_len++;\n\tvim_strncpy(syl->sy_chars, s, l);\n\tsyl->sy_len = l;\n }\n return OK;\n}",
"/*\n * Count the number of syllables in \"word\".\n * When \"word\" contains spaces the syllables after the last space are counted.\n * Returns zero if syllables are not defines.\n */\n static int\ncount_syllables(slang_T *slang, char_u *word)\n{\n int\t\tcnt = 0;\n int\t\tskip = FALSE;\n char_u\t*p;\n int\t\tlen;\n int\t\ti;\n syl_item_T\t*syl;\n int\t\tc;",
" if (slang->sl_syllable == NULL)\n\treturn 0;",
" for (p = word; *p != NUL; p += len)\n {\n\t// When running into a space reset counter.\n\tif (*p == ' ')\n\t{\n\t len = 1;\n\t cnt = 0;\n\t continue;\n\t}",
"\t// Find longest match of syllable items.\n\tlen = 0;\n\tfor (i = 0; i < slang->sl_syl_items.ga_len; ++i)\n\t{\n\t syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i;\n\t if (syl->sy_len > len\n\t\t\t && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0)\n\t\tlen = syl->sy_len;\n\t}\n\tif (len != 0)\t// found a match, count syllable\n\t{\n\t ++cnt;\n\t skip = FALSE;\n\t}\n\telse\n\t{\n\t // No recognized syllable item, at least a syllable char then?\n\t c = mb_ptr2char(p);\n\t len = (*mb_ptr2len)(p);\n\t if (vim_strchr(slang->sl_syllable, c) == NULL)\n\t\tskip = FALSE;\t // No, search for next syllable\n\t else if (!skip)\n\t {\n\t\t++cnt;\t\t // Yes, count it\n\t\tskip = TRUE;\t // don't count following syllable chars\n\t }\n\t}\n }\n return cnt;\n}",
"/*\n * Parse 'spelllang' and set w_s->b_langp accordingly.\n * Returns NULL if it's OK, an untranslated error message otherwise.\n */\n char *\ndid_set_spelllang(win_T *wp)\n{\n garray_T\tga;\n char_u\t*splp;\n char_u\t*region;\n char_u\tregion_cp[3];\n int\t\tfilename;\n int\t\tregion_mask;\n slang_T\t*slang;\n int\t\tc;\n char_u\tlang[MAXWLEN + 1];\n char_u\tspf_name[MAXPATHL];\n int\t\tlen;\n char_u\t*p;\n int\t\tround;\n char_u\t*spf;\n char_u\t*use_region = NULL;\n int\t\tdont_use_region = FALSE;\n int\t\tnobreak = FALSE;\n int\t\ti, j;\n langp_T\t*lp, *lp2;\n static int\trecursive = FALSE;\n char\t*ret_msg = NULL;\n char_u\t*spl_copy;\n bufref_T\tbufref;",
" set_bufref(&bufref, wp->w_buffer);",
" // We don't want to do this recursively. May happen when a language is\n // not available and the SpellFileMissing autocommand opens a new buffer\n // in which 'spell' is set.\n if (recursive)\n\treturn NULL;\n recursive = TRUE;",
" ga_init2(&ga, sizeof(langp_T), 2);\n clear_midword(wp);",
" // Make a copy of 'spelllang', the SpellFileMissing autocommands may change\n // it under our fingers.\n spl_copy = vim_strsave(wp->w_s->b_p_spl);\n if (spl_copy == NULL)\n\tgoto theend;",
" wp->w_s->b_cjk = 0;",
" // Loop over comma separated language names.\n for (splp = spl_copy; *splp != NUL; )\n {\n\t// Get one language name.\n\tcopy_option_part(&splp, lang, MAXWLEN, \",\");\n\tregion = NULL;\n\tlen = (int)STRLEN(lang);",
"\tif (!valid_spelllang(lang))\n\t continue;",
"\tif (STRCMP(lang, \"cjk\") == 0)\n\t{\n\t wp->w_s->b_cjk = 1;\n\t continue;\n\t}",
"\t// If the name ends in \".spl\" use it as the name of the spell file.\n\t// If there is a region name let \"region\" point to it and remove it\n\t// from the name.\n\tif (len > 4 && fnamecmp(lang + len - 4, \".spl\") == 0)\n\t{\n\t filename = TRUE;",
"\t // Locate a region and remove it from the file name.\n\t p = vim_strchr(gettail(lang), '_');\n\t if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2])\n\t\t\t\t\t\t && !ASCII_ISALPHA(p[3]))\n\t {\n\t\tvim_strncpy(region_cp, p + 1, 2);\n\t\tmch_memmove(p, p + 3, len - (p - lang) - 2);\n\t\tregion = region_cp;\n\t }\n\t else\n\t\tdont_use_region = TRUE;",
"\t // Check if we loaded this language before.\n\t FOR_ALL_SPELL_LANGS(slang)\n\t\tif (fullpathcmp(lang, slang->sl_fname, FALSE, TRUE) == FPC_SAME)\n\t\t break;\n\t}\n\telse\n\t{\n\t filename = FALSE;\n\t if (len > 3 && lang[len - 3] == '_')\n\t {\n\t\tregion = lang + len - 2;\n\t\tlen -= 3;\n\t\tlang[len] = NUL;\n\t }\n\t else\n\t\tdont_use_region = TRUE;",
"\t // Check if we loaded this language before.\n\t FOR_ALL_SPELL_LANGS(slang)\n\t\tif (STRICMP(lang, slang->sl_name) == 0)\n\t\t break;\n\t}",
"\tif (region != NULL)\n\t{\n\t // If the region differs from what was used before then don't\n\t // use it for 'spellfile'.\n\t if (use_region != NULL && STRCMP(region, use_region) != 0)\n\t\tdont_use_region = TRUE;\n\t use_region = region;\n\t}",
"\t// If not found try loading the language now.\n\tif (slang == NULL)\n\t{\n\t if (filename)\n\t\t(void)spell_load_file(lang, lang, NULL, FALSE);\n\t else\n\t {\n\t\tspell_load_lang(lang);\n\t\t// SpellFileMissing autocommands may do anything, including\n\t\t// destroying the buffer we are using...\n\t\tif (!bufref_valid(&bufref))\n\t\t{\n\t\t ret_msg = N_(e_spellfilemising_autocommand_deleted_buffer);\n\t\t goto theend;\n\t\t}\n\t }\n\t}",
"\t/*\n\t * Loop over the languages, there can be several files for \"lang\".\n\t */\n\tFOR_ALL_SPELL_LANGS(slang)\n\t if (filename ? fullpathcmp(lang, slang->sl_fname, FALSE, TRUE)\n\t\t\t\t\t\t\t\t == FPC_SAME\n\t\t\t : STRICMP(lang, slang->sl_name) == 0)\n\t {\n\t\tregion_mask = REGION_ALL;\n\t\tif (!filename && region != NULL)\n\t\t{\n\t\t // find region in sl_regions\n\t\t c = find_region(slang->sl_regions, region);\n\t\t if (c == REGION_ALL)\n\t\t {\n\t\t\tif (slang->sl_add)\n\t\t\t{\n\t\t\t if (*slang->sl_regions != NUL)\n\t\t\t\t// This addition file is for other regions.\n\t\t\t\tregion_mask = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t // This is probably an error. Give a warning and\n\t\t\t // accept the words anyway.\n\t\t\t smsg(_(\"Warning: region %s not supported\"),\n\t\t\t\t\t\t\t\t region);\n\t\t }\n\t\t else\n\t\t\tregion_mask = 1 << c;\n\t\t}",
"\t\tif (region_mask != 0)\n\t\t{\n\t\t if (ga_grow(&ga, 1) == FAIL)\n\t\t {\n\t\t\tga_clear(&ga);\n\t\t\tret_msg = e_out_of_memory;\n\t\t\tgoto theend;\n\t\t }\n\t\t LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;\n\t\t LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;\n\t\t ++ga.ga_len;\n\t\t use_midword(slang, wp);\n\t\t if (slang->sl_nobreak)\n\t\t\tnobreak = TRUE;\n\t\t}\n\t }\n }",
" // round 0: load int_wordlist, if possible.\n // round 1: load first name in 'spellfile'.\n // round 2: load second name in 'spellfile.\n // etc.\n spf = curwin->w_s->b_p_spf;\n for (round = 0; round == 0 || *spf != NUL; ++round)\n {\n\tif (round == 0)\n\t{\n\t // Internal wordlist, if there is one.\n\t if (int_wordlist == NULL)\n\t\tcontinue;\n\t int_wordlist_spl(spf_name);\n\t}\n\telse\n\t{\n\t // One entry in 'spellfile'.\n\t copy_option_part(&spf, spf_name, MAXPATHL - 5, \",\");\n\t STRCAT(spf_name, \".spl\");",
"\t // If it was already found above then skip it.\n\t for (c = 0; c < ga.ga_len; ++c)\n\t {\n\t\tp = LANGP_ENTRY(ga, c)->lp_slang->sl_fname;\n\t\tif (p != NULL && fullpathcmp(spf_name, p, FALSE, TRUE)\n\t\t\t\t\t\t\t\t== FPC_SAME)\n\t\t break;\n\t }\n\t if (c < ga.ga_len)\n\t\tcontinue;\n\t}",
"\t// Check if it was loaded already.\n\tFOR_ALL_SPELL_LANGS(slang)\n\t if (fullpathcmp(spf_name, slang->sl_fname, FALSE, TRUE)\n\t\t\t\t\t\t\t\t== FPC_SAME)\n\t\tbreak;\n\tif (slang == NULL)\n\t{\n\t // Not loaded, try loading it now. The language name includes the\n\t // region name, the region is ignored otherwise. for int_wordlist\n\t // use an arbitrary name.\n\t if (round == 0)\n\t\tSTRCPY(lang, \"internal wordlist\");\n\t else\n\t {\n\t\tvim_strncpy(lang, gettail(spf_name), MAXWLEN);\n\t\tp = vim_strchr(lang, '.');\n\t\tif (p != NULL)\n\t\t *p = NUL;\t// truncate at \".encoding.add\"\n\t }\n\t slang = spell_load_file(spf_name, lang, NULL, TRUE);",
"\t // If one of the languages has NOBREAK we assume the addition\n\t // files also have this.\n\t if (slang != NULL && nobreak)\n\t\tslang->sl_nobreak = TRUE;\n\t}\n\tif (slang != NULL && ga_grow(&ga, 1) == OK)\n\t{\n\t region_mask = REGION_ALL;\n\t if (use_region != NULL && !dont_use_region)\n\t {\n\t\t// find region in sl_regions\n\t\tc = find_region(slang->sl_regions, use_region);\n\t\tif (c != REGION_ALL)\n\t\t region_mask = 1 << c;\n\t\telse if (*slang->sl_regions != NUL)\n\t\t // This spell file is for other regions.\n\t\t region_mask = 0;\n\t }",
"\t if (region_mask != 0)\n\t {\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_sallang = NULL;\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_replang = NULL;\n\t\tLANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;\n\t\t++ga.ga_len;\n\t\tuse_midword(slang, wp);\n\t }\n\t}\n }",
" // Everything is fine, store the new b_langp value.\n ga_clear(&wp->w_s->b_langp);\n wp->w_s->b_langp = ga;",
" // For each language figure out what language to use for sound folding and\n // REP items. If the language doesn't support it itself use another one\n // with the same name. E.g. for \"en-math\" use \"en\".\n for (i = 0; i < ga.ga_len; ++i)\n {\n\tlp = LANGP_ENTRY(ga, i);",
"\t// sound folding\n\tif (lp->lp_slang->sl_sal.ga_len > 0)\n\t // language does sound folding itself\n\t lp->lp_sallang = lp->lp_slang;\n\telse\n\t // find first similar language that does sound folding\n\t for (j = 0; j < ga.ga_len; ++j)\n\t {\n\t\tlp2 = LANGP_ENTRY(ga, j);\n\t\tif (lp2->lp_slang->sl_sal.ga_len > 0\n\t\t\t&& STRNCMP(lp->lp_slang->sl_name,\n\t\t\t\t\t lp2->lp_slang->sl_name, 2) == 0)\n\t\t{\n\t\t lp->lp_sallang = lp2->lp_slang;\n\t\t break;\n\t\t}\n\t }",
"\t// REP items\n\tif (lp->lp_slang->sl_rep.ga_len > 0)\n\t // language has REP items itself\n\t lp->lp_replang = lp->lp_slang;\n\telse\n\t // find first similar language that has REP items\n\t for (j = 0; j < ga.ga_len; ++j)\n\t {\n\t\tlp2 = LANGP_ENTRY(ga, j);\n\t\tif (lp2->lp_slang->sl_rep.ga_len > 0\n\t\t\t&& STRNCMP(lp->lp_slang->sl_name,\n\t\t\t\t\t lp2->lp_slang->sl_name, 2) == 0)\n\t\t{\n\t\t lp->lp_replang = lp2->lp_slang;\n\t\t break;\n\t\t}\n\t }\n }\n redraw_win_later(wp, NOT_VALID);",
"theend:\n vim_free(spl_copy);\n recursive = FALSE;\n return ret_msg;\n}",
"/*\n * Clear the midword characters for buffer \"buf\".\n */\n static void\nclear_midword(win_T *wp)\n{\n CLEAR_FIELD(wp->w_s->b_spell_ismw);\n VIM_CLEAR(wp->w_s->b_spell_ismw_mb);\n}",
"/*\n * Use the \"sl_midword\" field of language \"lp\" for buffer \"buf\".\n * They add up to any currently used midword characters.\n */\n static void\nuse_midword(slang_T *lp, win_T *wp)\n{\n char_u\t*p;",
" if (lp->sl_midword == NULL)\t // there aren't any\n\treturn;",
" for (p = lp->sl_midword; *p != NUL; )\n\tif (has_mbyte)\n\t{\n\t int\t c, l, n;\n\t char_u *bp;",
"\t c = mb_ptr2char(p);\n\t l = (*mb_ptr2len)(p);\n\t if (c < 256 && l <= 2)\n\t\twp->w_s->b_spell_ismw[c] = TRUE;\n\t else if (wp->w_s->b_spell_ismw_mb == NULL)\n\t\t// First multi-byte char in \"b_spell_ismw_mb\".\n\t\twp->w_s->b_spell_ismw_mb = vim_strnsave(p, l);\n\t else\n\t {\n\t\t// Append multi-byte chars to \"b_spell_ismw_mb\".\n\t\tn = (int)STRLEN(wp->w_s->b_spell_ismw_mb);\n\t\tbp = vim_strnsave(wp->w_s->b_spell_ismw_mb, n + l);\n\t\tif (bp != NULL)\n\t\t{\n\t\t vim_free(wp->w_s->b_spell_ismw_mb);\n\t\t wp->w_s->b_spell_ismw_mb = bp;\n\t\t vim_strncpy(bp + n, p, l);\n\t\t}\n\t }\n\t p += l;\n\t}\n\telse\n\t wp->w_s->b_spell_ismw[*p++] = TRUE;\n}",
"/*\n * Find the region \"region[2]\" in \"rp\" (points to \"sl_regions\").\n * Each region is simply stored as the two characters of its name.\n * Returns the index if found (first is 0), REGION_ALL if not found.\n */\n static int\nfind_region(char_u *rp, char_u *region)\n{\n int\t\ti;",
" for (i = 0; ; i += 2)\n {\n\tif (rp[i] == NUL)\n\t return REGION_ALL;\n\tif (rp[i] == region[0] && rp[i + 1] == region[1])\n\t break;\n }\n return i / 2;\n}",
"/*\n * Return case type of word:\n * w word\t0\n * Word\t\tWF_ONECAP\n * W WORD\tWF_ALLCAP\n * WoRd\twOrd\tWF_KEEPCAP\n */\n int\ncaptype(\n char_u\t*word,\n char_u\t*end)\t // When NULL use up to NUL byte.\n{\n char_u\t*p;\n int\t\tc;\n int\t\tfirstcap;\n int\t\tallcap;\n int\t\tpast_second = FALSE;\t// past second word char",
" // find first letter\n for (p = word; !spell_iswordp_nmw(p, curwin); MB_PTR_ADV(p))\n\tif (end == NULL ? *p == NUL : p >= end)\n\t return 0;\t // only non-word characters, illegal word\n if (has_mbyte)\n\tc = mb_ptr2char_adv(&p);\n else\n\tc = *p++;\n firstcap = allcap = SPELL_ISUPPER(c);",
" /*\n * Need to check all letters to find a word with mixed upper/lower.\n * But a word with an upper char only at start is a ONECAP.\n */\n for ( ; end == NULL ? *p != NUL : p < end; MB_PTR_ADV(p))\n\tif (spell_iswordp_nmw(p, curwin))\n\t{\n\t c = PTR2CHAR(p);\n\t if (!SPELL_ISUPPER(c))\n\t {\n\t\t// UUl -> KEEPCAP\n\t\tif (past_second && allcap)\n\t\t return WF_KEEPCAP;\n\t\tallcap = FALSE;\n\t }\n\t else if (!allcap)\n\t\t// UlU -> KEEPCAP\n\t\treturn WF_KEEPCAP;\n\t past_second = TRUE;\n\t}",
" if (allcap)\n\treturn WF_ALLCAP;\n if (firstcap)\n\treturn WF_ONECAP;\n return 0;\n}",
"/*\n * Delete the internal wordlist and its .spl file.\n */\n void\nspell_delete_wordlist(void)\n{\n char_u\tfname[MAXPATHL];",
" if (int_wordlist != NULL)\n {\n\tmch_remove(int_wordlist);\n\tint_wordlist_spl(fname);\n\tmch_remove(fname);\n\tVIM_CLEAR(int_wordlist);\n }\n}",
"/*\n * Free all languages.\n */\n void\nspell_free_all(void)\n{\n slang_T\t*slang;\n buf_T\t*buf;",
" // Go through all buffers and handle 'spelllang'. <VN>\n FOR_ALL_BUFFERS(buf)\n\tga_clear(&buf->b_s.b_langp);",
" while (first_lang != NULL)\n {\n\tslang = first_lang;\n\tfirst_lang = slang->sl_next;\n\tslang_free(slang);\n }",
" spell_delete_wordlist();",
" VIM_CLEAR(repl_to);\n VIM_CLEAR(repl_from);\n}",
"/*\n * Clear all spelling tables and reload them.\n * Used after 'encoding' is set and when \":mkspell\" was used.\n */\n void\nspell_reload(void)\n{\n win_T\t*wp;",
" // Initialize the table for spell_iswordp().\n init_spell_chartab();",
" // Unload all allocated memory.\n spell_free_all();",
" // Go through all buffers and handle 'spelllang'.\n FOR_ALL_WINDOWS(wp)\n {\n\t// Only load the wordlists when 'spelllang' is set and there is a\n\t// window for this buffer in which 'spell' is set.\n\tif (*wp->w_s->b_p_spl != NUL)\n\t{\n\t\tif (wp->w_p_spell)\n\t\t{\n\t\t (void)did_set_spelllang(wp);\n\t\t break;\n\t\t}\n\t}\n }\n}",
"/*\n * Open a spell buffer. This is a nameless buffer that is not in the buffer\n * list and only contains text lines. Can use a swapfile to reduce memory\n * use.\n * Most other fields are invalid! Esp. watch out for string options being\n * NULL and there is no undo info.\n * Returns NULL when out of memory.\n */\n buf_T *\nopen_spellbuf(void)\n{\n buf_T\t*buf;",
" buf = ALLOC_CLEAR_ONE(buf_T);\n if (buf != NULL)\n {\n\tbuf->b_spell = TRUE;\n\tbuf->b_p_swf = TRUE;\t// may create a swap file\n#ifdef FEAT_CRYPT\n\tbuf->b_p_key = empty_option;\n#endif\n\tml_open(buf);\n\tml_open_file(buf);\t// create swap file now\n }\n return buf;\n}",
"/*\n * Close the buffer used for spell info.\n */\n void\nclose_spellbuf(buf_T *buf)\n{\n if (buf != NULL)\n {\n\tml_close(buf, TRUE);\n\tvim_free(buf);\n }\n}",
"/*\n * Init the chartab used for spelling for ASCII.\n */\n void\nclear_spell_chartab(spelltab_T *sp)\n{\n int\t\ti;",
" // Init everything to FALSE (zero).\n CLEAR_FIELD(sp->st_isw);\n CLEAR_FIELD(sp->st_isu);\n for (i = 0; i < 256; ++i)\n {\n\tsp->st_fold[i] = i;\n\tsp->st_upper[i] = i;\n }",
" // We include digits. A word shouldn't start with a digit, but handling\n // that is done separately.\n for (i = '0'; i <= '9'; ++i)\n\tsp->st_isw[i] = TRUE;\n for (i = 'A'; i <= 'Z'; ++i)\n {\n\tsp->st_isw[i] = TRUE;\n\tsp->st_isu[i] = TRUE;\n\tsp->st_fold[i] = i + 0x20;\n }\n for (i = 'a'; i <= 'z'; ++i)\n {\n\tsp->st_isw[i] = TRUE;\n\tsp->st_upper[i] = i - 0x20;\n }\n}",
"/*\n * Init the chartab used for spelling. Only depends on 'encoding'.\n * Called once while starting up and when 'encoding' changes.\n * The default is to use isalpha(), but the spell file should define the word\n * characters to make it possible that 'encoding' differs from the current\n * locale. For utf-8 we don't use isalpha() but our own functions.\n */\n void\ninit_spell_chartab(void)\n{\n int\t i;",
" did_set_spelltab = FALSE;\n clear_spell_chartab(&spelltab);\n if (enc_dbcs)\n {\n\t// DBCS: assume double-wide characters are word characters.\n\tfor (i = 128; i <= 255; ++i)\n\t if (MB_BYTE2LEN(i) == 2)\n\t\tspelltab.st_isw[i] = TRUE;\n }\n else if (enc_utf8)\n {\n\tfor (i = 128; i < 256; ++i)\n\t{\n\t int f = utf_fold(i);\n\t int u = utf_toupper(i);",
"\t spelltab.st_isu[i] = utf_isupper(i);\n\t spelltab.st_isw[i] = spelltab.st_isu[i] || utf_islower(i);\n\t // The folded/upper-cased value is different between latin1 and\n\t // utf8 for 0xb5, causing E763 for no good reason. Use the latin1\n\t // value for utf-8 to avoid this.\n\t spelltab.st_fold[i] = (f < 256) ? f : i;\n\t spelltab.st_upper[i] = (u < 256) ? u : i;\n\t}\n }\n else\n {\n\t// Rough guess: use locale-dependent library functions.\n\tfor (i = 128; i < 256; ++i)\n\t{\n\t if (MB_ISUPPER(i))\n\t {\n\t\tspelltab.st_isw[i] = TRUE;\n\t\tspelltab.st_isu[i] = TRUE;\n\t\tspelltab.st_fold[i] = MB_TOLOWER(i);\n\t }\n\t else if (MB_ISLOWER(i))\n\t {\n\t\tspelltab.st_isw[i] = TRUE;\n\t\tspelltab.st_upper[i] = MB_TOUPPER(i);\n\t }\n\t}\n }\n}",
"\n/*\n * Return TRUE if \"p\" points to a word character.\n * As a special case we see \"midword\" characters as word character when it is\n * followed by a word character. This finds they'there but not 'they there'.\n * Thus this only works properly when past the first character of the word.\n */\n int\nspell_iswordp(\n char_u\t*p,\n win_T\t*wp)\t // buffer used\n{\n char_u\t*s;\n int\t\tl;\n int\t\tc;",
" if (has_mbyte)\n {\n\tl = mb_ptr2len(p);\n\ts = p;\n\tif (l == 1)\n\t{\n\t // be quick for ASCII\n\t if (wp->w_s->b_spell_ismw[*p])\n\t\ts = p + 1;\t\t// skip a mid-word character\n\t}\n\telse\n\t{\n\t c = mb_ptr2char(p);\n\t if (c < 256 ? wp->w_s->b_spell_ismw[c]\n\t\t : (wp->w_s->b_spell_ismw_mb != NULL\n\t\t\t && vim_strchr(wp->w_s->b_spell_ismw_mb, c) != NULL))\n\t\ts = p + l;\n\t}",
"\tc = mb_ptr2char(s);\n\tif (c > 255)\n\t return spell_mb_isword_class(mb_get_class(s), wp);\n\treturn spelltab.st_isw[c];\n }",
" return spelltab.st_isw[wp->w_s->b_spell_ismw[*p] ? p[1] : p[0]];\n}",
"/*\n * Return TRUE if \"p\" points to a word character.\n * Unlike spell_iswordp() this doesn't check for \"midword\" characters.\n */\n int\nspell_iswordp_nmw(char_u *p, win_T *wp)\n{\n int\t\tc;",
" if (has_mbyte)\n {\n\tc = mb_ptr2char(p);\n\tif (c > 255)\n\t return spell_mb_isword_class(mb_get_class(p), wp);\n\treturn spelltab.st_isw[c];\n }\n return spelltab.st_isw[*p];\n}",
"/*\n * Return TRUE if word class indicates a word character.\n * Only for characters above 255.\n * Unicode subscript and superscript are not considered word characters.\n * See also dbcs_class() and utf_class() in mbyte.c.\n */\n static int\nspell_mb_isword_class(int cl, win_T *wp)\n{\n if (wp->w_s->b_cjk)\n\t// East Asian characters are not considered word characters.\n\treturn cl == 2 || cl == 0x2800;\n return cl >= 2 && cl != 0x2070 && cl != 0x2080 && cl != 3;\n}",
"/*\n * Return TRUE if \"p\" points to a word character.\n * Wide version of spell_iswordp().\n */\n static int\nspell_iswordp_w(int *p, win_T *wp)\n{\n int\t\t*s;",
" if (*p < 256 ? wp->w_s->b_spell_ismw[*p]\n\t\t : (wp->w_s->b_spell_ismw_mb != NULL\n\t\t\t && vim_strchr(wp->w_s->b_spell_ismw_mb, *p) != NULL))\n\ts = p + 1;\n else\n\ts = p;",
" if (*s > 255)\n {\n\tif (enc_utf8)\n\t return spell_mb_isword_class(utf_class(*s), wp);\n\tif (enc_dbcs)\n\t return spell_mb_isword_class(\n\t\t\t\tdbcs_class((unsigned)*s >> 8, *s & 0xff), wp);\n\treturn 0;\n }\n return spelltab.st_isw[*s];\n}",
"/*\n * Case-fold \"str[len]\" into \"buf[buflen]\". The result is NUL terminated.\n * Uses the character definitions from the .spl file.\n * When using a multi-byte 'encoding' the length may change!\n * Returns FAIL when something wrong.\n */\n int\nspell_casefold(\n win_T\t*wp,\n char_u\t*str,\n int\t\tlen,\n char_u\t*buf,\n int\t\tbuflen)\n{\n int\t\ti;",
" if (len >= buflen)\n {\n\tbuf[0] = NUL;\n\treturn FAIL;\t\t// result will not fit\n }",
" if (has_mbyte)\n {\n\tint\touti = 0;\n\tchar_u\t*p;\n\tint\tc;",
"\t// Fold one character at a time.\n\tfor (p = str; p < str + len; )\n\t{\n\t if (outi + MB_MAXBYTES > buflen)\n\t {\n\t\tbuf[outi] = NUL;\n\t\treturn FAIL;\n\t }\n\t c = mb_cptr2char_adv(&p);",
"\t // Exception: greek capital sigma 0x03A3 folds to 0x03C3, except\n\t // when it is the last character in a word, then it folds to\n\t // 0x03C2.\n\t if (c == 0x03a3 || c == 0x03c2)\n\t {\n\t\tif (p == str + len || !spell_iswordp(p, wp))\n\t\t c = 0x03c2;\n\t\telse\n\t\t c = 0x03c3;\n\t }\n\t else\n\t\tc = SPELL_TOFOLD(c);",
"\t outi += mb_char2bytes(c, buf + outi);\n\t}\n\tbuf[outi] = NUL;\n }\n else\n {\n\t// Be quick for non-multibyte encodings.\n\tfor (i = 0; i < len; ++i)\n\t buf[i] = spelltab.st_fold[str[i]];\n\tbuf[i] = NUL;\n }",
" return OK;\n}",
"/*\n * Check if the word at line \"lnum\" column \"col\" is required to start with a\n * capital. This uses 'spellcapcheck' of the current buffer.\n */\n int\ncheck_need_cap(linenr_T lnum, colnr_T col)\n{\n int\t\tneed_cap = FALSE;\n char_u\t*line;\n char_u\t*line_copy = NULL;\n char_u\t*p;\n colnr_T\tendcol;\n regmatch_T\tregmatch;",
" if (curwin->w_s->b_cap_prog == NULL)\n\treturn FALSE;",
" line = ml_get_curline();\n endcol = 0;\n if (getwhitecols(line) >= (int)col)\n {\n\t// At start of line, check if previous line is empty or sentence\n\t// ends there.\n\tif (lnum == 1)\n\t need_cap = TRUE;\n\telse\n\t{\n\t line = ml_get(lnum - 1);\n\t if (*skipwhite(line) == NUL)\n\t\tneed_cap = TRUE;\n\t else\n\t {\n\t\t// Append a space in place of the line break.\n\t\tline_copy = concat_str(line, (char_u *)\" \");\n\t\tline = line_copy;\n\t\tendcol = (colnr_T)STRLEN(line);\n\t }\n\t}\n }\n else\n\tendcol = col;",
" if (endcol > 0)\n {\n\t// Check if sentence ends before the bad word.\n\tregmatch.regprog = curwin->w_s->b_cap_prog;\n\tregmatch.rm_ic = FALSE;\n\tp = line + endcol;\n\tfor (;;)\n\t{\n\t MB_PTR_BACK(line, p);\n\t if (p == line || spell_iswordp_nmw(p, curwin))\n\t\tbreak;\n\t if (vim_regexec(®match, p, 0)\n\t\t\t\t\t && regmatch.endp[0] == line + endcol)\n\t {\n\t\tneed_cap = TRUE;\n\t\tbreak;\n\t }\n\t}\n\tcurwin->w_s->b_cap_prog = regmatch.regprog;\n }",
" vim_free(line_copy);",
" return need_cap;\n}",
"\n/*\n * \":spellrepall\"\n */\n void\nex_spellrepall(exarg_T *eap UNUSED)\n{\n pos_T\tpos = curwin->w_cursor;\n char_u\t*frompat;\n int\t\taddlen;\n char_u\t*line;\n char_u\t*p;\n int\t\tsave_ws = p_ws;\n linenr_T\tprev_lnum = 0;",
" if (repl_from == NULL || repl_to == NULL)\n {\n\temsg(_(e_no_previous_spell_replacement));\n\treturn;\n }\n addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from));",
" frompat = alloc(STRLEN(repl_from) + 7);\n if (frompat == NULL)\n\treturn;\n sprintf((char *)frompat, \"\\\\V\\\\<%s\\\\>\", repl_from);\n p_ws = FALSE;",
" sub_nsubs = 0;\n sub_nlines = 0;\n curwin->w_cursor.lnum = 0;\n while (!got_int)\n {\n\tif (do_search(NULL, '/', '/', frompat, 1L, SEARCH_KEEP, NULL) == 0\n\t\t\t\t\t\t || u_save_cursor() == FAIL)\n\t break;",
"\t// Only replace when the right word isn't there yet. This happens\n\t// when changing \"etc\" to \"etc.\".\n\tline = ml_get_curline();\n\tif (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col,\n\t\t\t\t\t repl_to, STRLEN(repl_to)) != 0)\n\t{\n\t p = alloc(STRLEN(line) + addlen + 1);\n\t if (p == NULL)\n\t\tbreak;\n\t mch_memmove(p, line, curwin->w_cursor.col);\n\t STRCPY(p + curwin->w_cursor.col, repl_to);\n\t STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from));\n\t ml_replace(curwin->w_cursor.lnum, p, FALSE);\n\t changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);\n\t if (curbuf->b_has_textprop && addlen != 0)\n\t\tadjust_prop_columns(curwin->w_cursor.lnum,\n\t\t\t\t curwin->w_cursor.col, addlen, APC_SUBSTITUTE);",
"\t if (curwin->w_cursor.lnum != prev_lnum)\n\t {\n\t\t++sub_nlines;\n\t\tprev_lnum = curwin->w_cursor.lnum;\n\t }\n\t ++sub_nsubs;\n\t}\n\tcurwin->w_cursor.col += (colnr_T)STRLEN(repl_to);\n }",
" p_ws = save_ws;\n curwin->w_cursor = pos;\n vim_free(frompat);",
" if (sub_nsubs == 0)\n\tsemsg(_(e_not_found_str), repl_from);\n else\n\tdo_sub_msg(FALSE);\n}",
"/*\n * Make a copy of \"word\", with the first letter upper or lower cased, to\n * \"wcopy[MAXWLEN]\". \"word\" must not be empty.\n * The result is NUL terminated.\n */\n void\nonecap_copy(\n char_u\t*word,\n char_u\t*wcopy,\n int\t\tupper)\t // TRUE: first letter made upper case\n{\n char_u\t*p;\n int\t\tc;\n int\t\tl;",
" p = word;\n if (has_mbyte)\n\tc = mb_cptr2char_adv(&p);\n else\n\tc = *p++;\n if (upper)\n\tc = SPELL_TOUPPER(c);\n else\n\tc = SPELL_TOFOLD(c);\n if (has_mbyte)\n\tl = mb_char2bytes(c, wcopy);\n else\n {\n\tl = 1;\n\twcopy[0] = c;\n }\n vim_strncpy(wcopy + l, p, MAXWLEN - l - 1);\n}",
"/*\n * Make a copy of \"word\" with all the letters upper cased into\n * \"wcopy[MAXWLEN]\". The result is NUL terminated.\n */\n void\nallcap_copy(char_u *word, char_u *wcopy)\n{\n char_u\t*s;\n char_u\t*d;\n int\t\tc;",
" d = wcopy;\n for (s = word; *s != NUL; )\n {\n\tif (has_mbyte)\n\t c = mb_cptr2char_adv(&s);\n\telse\n\t c = *s++;",
"\t// We only change 0xdf to SS when we are certain latin1 is used. It\n\t// would cause weird errors in other 8-bit encodings.\n\tif (enc_latin1like && c == 0xdf)\n\t{\n\t c = 'S';\n\t if (d - wcopy >= MAXWLEN - 1)\n\t\tbreak;\n\t *d++ = c;\n\t}\n\telse\n\t c = SPELL_TOUPPER(c);",
"\tif (has_mbyte)\n\t{\n\t if (d - wcopy >= MAXWLEN - MB_MAXBYTES)\n\t\tbreak;\n\t d += mb_char2bytes(c, d);\n\t}\n\telse\n\t{\n\t if (d - wcopy >= MAXWLEN - 1)\n\t\tbreak;\n\t *d++ = c;\n\t}\n }\n *d = NUL;\n}",
"/*\n * Case-folding may change the number of bytes: Count nr of chars in\n * fword[flen] and return the byte length of that many chars in \"word\".\n */\n int\nnofold_len(char_u *fword, int flen, char_u *word)\n{\n char_u\t*p;\n int\t\ti = 0;",
" for (p = fword; p < fword + flen; MB_PTR_ADV(p))\n\t++i;\n for (p = word; i > 0; MB_PTR_ADV(p))\n\t--i;\n return (int)(p - word);\n}",
"/*\n * Copy \"fword\" to \"cword\", fixing case according to \"flags\".\n */\n void\nmake_case_word(char_u *fword, char_u *cword, int flags)\n{\n if (flags & WF_ALLCAP)\n\t// Make it all upper-case\n\tallcap_copy(fword, cword);\n else if (flags & WF_ONECAP)\n\t// Make the first letter upper-case\n\tonecap_copy(fword, cword, TRUE);\n else\n\t// Use goodword as-is.\n\tSTRCPY(cword, fword);\n}",
"#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Soundfold a string, for soundfold().\n * Result is in allocated memory, NULL for an error.\n */\n char_u *\neval_soundfold(char_u *word)\n{\n langp_T\t*lp;\n char_u\tsound[MAXWLEN];\n int\t\tlpi;",
" if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)\n\t// Use the sound-folding of the first language that supports it.\n\tfor (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)\n\t{\n\t lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\t if (lp->lp_slang->sl_sal.ga_len > 0)\n\t {\n\t\t// soundfold the word\n\t\tspell_soundfold(lp->lp_slang, word, FALSE, sound);\n\t\treturn vim_strsave(sound);\n\t }\n\t}",
" // No language with sound folding, return word as-is.\n return vim_strsave(word);\n}\n#endif",
"/*\n * Turn \"inword\" into its sound-a-like equivalent in \"res[MAXWLEN]\".\n *\n * There are many ways to turn a word into a sound-a-like representation. The\n * oldest is Soundex (1918!). A nice overview can be found in \"Approximate\n * swedish name matching - survey and test of different algorithms\" by Klas\n * Erikson.\n *\n * We support two methods:\n * 1. SOFOFROM/SOFOTO do a simple character mapping.\n * 2. SAL items define a more advanced sound-folding (and much slower).\n */\n void\nspell_soundfold(\n slang_T\t*slang,\n char_u\t*inword,\n int\t\tfolded,\t // \"inword\" is already case-folded\n char_u\t*res)\n{\n char_u\tfword[MAXWLEN];\n char_u\t*word;",
" if (slang->sl_sofo)\n\t// SOFOFROM and SOFOTO used\n\tspell_soundfold_sofo(slang, inword, res);\n else\n {\n\t// SAL items used. Requires the word to be case-folded.\n\tif (folded)\n\t word = inword;\n\telse\n\t{\n\t (void)spell_casefold(curwin,\n\t\t\t\t inword, (int)STRLEN(inword), fword, MAXWLEN);\n\t word = fword;\n\t}",
"\tif (has_mbyte)\n\t spell_soundfold_wsal(slang, word, res);\n\telse\n\t spell_soundfold_sal(slang, word, res);\n }\n}",
"/*\n * Perform sound folding of \"inword\" into \"res\" according to SOFOFROM and\n * SOFOTO lines.\n */\n static void\nspell_soundfold_sofo(slang_T *slang, char_u *inword, char_u *res)\n{\n char_u\t*s;\n int\t\tri = 0;\n int\t\tc;",
" if (has_mbyte)\n {\n\tint\tprevc = 0;\n\tint\t*ip;",
"\t// The sl_sal_first[] table contains the translation for chars up to\n\t// 255, sl_sal the rest.\n\tfor (s = inword; *s != NUL; )\n\t{\n\t c = mb_cptr2char_adv(&s);\n\t if (enc_utf8 ? utf_class(c) == 0 : VIM_ISWHITE(c))\n\t\tc = ' ';\n\t else if (c < 256)\n\t\tc = slang->sl_sal_first[c];\n\t else\n\t {\n\t\tip = ((int **)slang->sl_sal.ga_data)[c & 0xff];\n\t\tif (ip == NULL)\t\t// empty list, can't match\n\t\t c = NUL;\n\t\telse\n\t\t for (;;)\t\t// find \"c\" in the list\n\t\t {\n\t\t\tif (*ip == 0)\t// not found\n\t\t\t{\n\t\t\t c = NUL;\n\t\t\t break;\n\t\t\t}\n\t\t\tif (*ip == c)\t// match!\n\t\t\t{\n\t\t\t c = ip[1];\n\t\t\t break;\n\t\t\t}\n\t\t\tip += 2;\n\t\t }\n\t }",
"\t if (c != NUL && c != prevc)\n\t {\n\t\tri += mb_char2bytes(c, res + ri);\n\t\tif (ri + MB_MAXBYTES > MAXWLEN)\n\t\t break;\n\t\tprevc = c;\n\t }\n\t}\n }\n else\n {\n\t// The sl_sal_first[] table contains the translation.\n\tfor (s = inword; (c = *s) != NUL; ++s)\n\t{\n\t if (VIM_ISWHITE(c))\n\t\tc = ' ';\n\t else\n\t\tc = slang->sl_sal_first[c];\n\t if (c != NUL && (ri == 0 || res[ri - 1] != c))\n\t\tres[ri++] = c;\n\t}\n }",
" res[ri] = NUL;\n}",
" static void\nspell_soundfold_sal(slang_T *slang, char_u *inword, char_u *res)\n{\n salitem_T\t*smp;\n char_u\tword[MAXWLEN];\n char_u\t*s = inword;\n char_u\t*t;\n char_u\t*pf;\n int\t\ti, j, z;\n int\t\treslen;\n int\t\tn, k = 0;\n int\t\tz0;\n int\t\tk0;\n int\t\tn0;\n int\t\tc;\n int\t\tpri;\n int\t\tp0 = -333;\n int\t\tc0;",
" // Remove accents, if wanted. We actually remove all non-word characters.\n // But keep white space. We need a copy, the word may be changed here.\n if (slang->sl_rem_accents)\n {\n\tt = word;\n\twhile (*s != NUL)\n\t{\n\t if (VIM_ISWHITE(*s))\n\t {\n\t\t*t++ = ' ';\n\t\ts = skipwhite(s);\n\t }\n\t else\n\t {\n\t\tif (spell_iswordp_nmw(s, curwin))\n\t\t *t++ = *s;\n\t\t++s;\n\t }\n\t}\n\t*t = NUL;\n }\n else\n\tvim_strncpy(word, s, MAXWLEN - 1);",
" smp = (salitem_T *)slang->sl_sal.ga_data;",
" /*\n * This comes from Aspell phonet.cpp. Converted from C++ to C.\n * Changed to keep spaces.\n */\n i = reslen = z = 0;\n while ((c = word[i]) != NUL)\n {\n\t// Start with the first rule that has the character in the word.\n\tn = slang->sl_sal_first[c];\n\tz0 = 0;",
"\tif (n >= 0)\n\t{\n\t // check all rules for the same letter\n\t for (; (s = smp[n].sm_lead)[0] == c; ++n)\n\t {\n\t\t// Quickly skip entries that don't match the word. Most\n\t\t// entries are less than three chars, optimize for that.\n\t\tk = smp[n].sm_leadlen;\n\t\tif (k > 1)\n\t\t{\n\t\t if (word[i + 1] != s[1])\n\t\t\tcontinue;\n\t\t if (k > 2)\n\t\t {\n\t\t\tfor (j = 2; j < k; ++j)\n\t\t\t if (word[i + j] != s[j])\n\t\t\t\tbreak;\n\t\t\tif (j < k)\n\t\t\t continue;\n\t\t }\n\t\t}",
"\t\tif ((pf = smp[n].sm_oneof) != NULL)\n\t\t{\n\t\t // Check for match with one of the chars in \"sm_oneof\".\n\t\t while (*pf != NUL && *pf != word[i + k])\n\t\t\t++pf;\n\t\t if (*pf == NUL)\n\t\t\tcontinue;\n\t\t ++k;\n\t\t}\n\t\ts = smp[n].sm_rules;\n\t\tpri = 5; // default priority",
"\t\tp0 = *s;\n\t\tk0 = k;\n\t\twhile (*s == '-' && k > 1)\n\t\t{\n\t\t k--;\n\t\t s++;\n\t\t}\n\t\tif (*s == '<')\n\t\t s++;\n\t\tif (VIM_ISDIGIT(*s))\n\t\t{\n\t\t // determine priority\n\t\t pri = *s - '0';\n\t\t s++;\n\t\t}\n\t\tif (*s == '^' && *(s + 1) == '^')\n\t\t s++;",
"\t\tif (*s == NUL\n\t\t\t|| (*s == '^'\n\t\t\t && (i == 0 || !(word[i - 1] == ' '\n\t\t\t\t || spell_iswordp(word + i - 1, curwin)))\n\t\t\t && (*(s + 1) != '$'\n\t\t\t\t|| (!spell_iswordp(word + i + k0, curwin))))\n\t\t\t|| (*s == '$' && i > 0\n\t\t\t && spell_iswordp(word + i - 1, curwin)\n\t\t\t && (!spell_iswordp(word + i + k0, curwin))))\n\t\t{\n\t\t // search for followup rules, if:\n\t\t // followup and k > 1 and NO '-' in searchstring\n\t\t c0 = word[i + k - 1];\n\t\t n0 = slang->sl_sal_first[c0];",
"\t\t if (slang->sl_followup && k > 1 && n0 >= 0\n\t\t\t\t\t && p0 != '-' && word[i + k] != NUL)\n\t\t {\n\t\t\t// test follow-up rule for \"word[i + k]\"\n\t\t\tfor ( ; (s = smp[n0].sm_lead)[0] == c0; ++n0)\n\t\t\t{\n\t\t\t // Quickly skip entries that don't match the word.\n\t\t\t //\n\t\t\t k0 = smp[n0].sm_leadlen;\n\t\t\t if (k0 > 1)\n\t\t\t {\n\t\t\t\tif (word[i + k] != s[1])\n\t\t\t\t continue;\n\t\t\t\tif (k0 > 2)\n\t\t\t\t{\n\t\t\t\t pf = word + i + k + 1;\n\t\t\t\t for (j = 2; j < k0; ++j)\n\t\t\t\t\tif (*pf++ != s[j])\n\t\t\t\t\t break;\n\t\t\t\t if (j < k0)\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t }\n\t\t\t k0 += k - 1;",
"\t\t\t if ((pf = smp[n0].sm_oneof) != NULL)\n\t\t\t {\n\t\t\t\t// Check for match with one of the chars in\n\t\t\t\t// \"sm_oneof\".\n\t\t\t\twhile (*pf != NUL && *pf != word[i + k0])\n\t\t\t\t ++pf;\n\t\t\t\tif (*pf == NUL)\n\t\t\t\t continue;\n\t\t\t\t++k0;\n\t\t\t }",
"\t\t\t p0 = 5;\n\t\t\t s = smp[n0].sm_rules;\n\t\t\t while (*s == '-')\n\t\t\t {\n\t\t\t\t// \"k0\" gets NOT reduced because\n\t\t\t\t// \"if (k0 == k)\"\n\t\t\t\ts++;\n\t\t\t }\n\t\t\t if (*s == '<')\n\t\t\t\ts++;\n\t\t\t if (VIM_ISDIGIT(*s))\n\t\t\t {\n\t\t\t\tp0 = *s - '0';\n\t\t\t\ts++;\n\t\t\t }",
"\t\t\t if (*s == NUL\n\t\t\t\t // *s == '^' cuts\n\t\t\t\t || (*s == '$'\n\t\t\t\t\t && !spell_iswordp(word + i + k0,\n\t\t\t\t\t\t\t\t curwin)))\n\t\t\t {\n\t\t\t\tif (k0 == k)\n\t\t\t\t // this is just a piece of the string\n\t\t\t\t continue;",
"\t\t\t\tif (p0 < pri)\n\t\t\t\t // priority too low\n\t\t\t\t continue;\n\t\t\t\t// rule fits; stop search\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}",
"\t\t\tif (p0 >= pri && smp[n0].sm_lead[0] == c0)\n\t\t\t continue;\n\t\t }",
"\t\t // replace string\n\t\t s = smp[n].sm_to;\n\t\t if (s == NULL)\n\t\t\ts = (char_u *)\"\";\n\t\t pf = smp[n].sm_rules;\n\t\t p0 = (vim_strchr(pf, '<') != NULL) ? 1 : 0;\n\t\t if (p0 == 1 && z == 0)\n\t\t {\n\t\t\t// rule with '<' is used\n\t\t\tif (reslen > 0 && *s != NUL && (res[reslen - 1] == c\n\t\t\t\t\t\t || res[reslen - 1] == *s))\n\t\t\t reslen--;\n\t\t\tz0 = 1;\n\t\t\tz = 1;\n\t\t\tk0 = 0;\n\t\t\twhile (*s != NUL && word[i + k0] != NUL)\n\t\t\t{\n\t\t\t word[i + k0] = *s;\n\t\t\t k0++;\n\t\t\t s++;\n\t\t\t}\n\t\t\tif (k > k0)\n\t\t\t STRMOVE(word + i + k0, word + i + k);",
"\t\t\t// new \"actual letter\"\n\t\t\tc = word[i];\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// no '<' rule used\n\t\t\ti += k - 1;\n\t\t\tz = 0;\n\t\t\twhile (*s != NUL && s[1] != NUL && reslen < MAXWLEN)\n\t\t\t{\n\t\t\t if (reslen == 0 || res[reslen - 1] != *s)\n\t\t\t\tres[reslen++] = *s;\n\t\t\t s++;\n\t\t\t}\n\t\t\t// new \"actual letter\"\n\t\t\tc = *s;\n\t\t\tif (strstr((char *)pf, \"^^\") != NULL)\n\t\t\t{\n\t\t\t if (c != NUL)\n\t\t\t\tres[reslen++] = c;\n\t\t\t STRMOVE(word, word + i + 1);\n\t\t\t i = 0;\n\t\t\t z0 = 1;\n\t\t\t}\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\t}\n\telse if (VIM_ISWHITE(c))\n\t{\n\t c = ' ';\n\t k = 1;\n\t}",
"\tif (z0 == 0)\n\t{\n\t if (k && !p0 && reslen < MAXWLEN && c != NUL\n\t\t && (!slang->sl_collapse || reslen == 0\n\t\t\t\t\t\t || res[reslen - 1] != c))\n\t\t// condense only double letters\n\t\tres[reslen++] = c;",
"\t i++;\n\t z = 0;\n\t k = 0;\n\t}\n }",
" res[reslen] = NUL;\n}",
"/*\n * Turn \"inword\" into its sound-a-like equivalent in \"res[MAXWLEN]\".\n * Multi-byte version of spell_soundfold().\n */\n static void\nspell_soundfold_wsal(slang_T *slang, char_u *inword, char_u *res)\n{\n salitem_T\t*smp = (salitem_T *)slang->sl_sal.ga_data;\n int\t\tword[MAXWLEN];\n int\t\twres[MAXWLEN];\n int\t\tl;\n char_u\t*s;\n int\t\t*ws;\n char_u\t*t;\n int\t\t*pf;\n int\t\ti, j, z;\n int\t\treslen;\n int\t\tn, k = 0;\n int\t\tz0;\n int\t\tk0;\n int\t\tn0;\n int\t\tc;\n int\t\tpri;\n int\t\tp0 = -333;\n int\t\tc0;\n int\t\tdid_white = FALSE;\n int\t\twordlen;",
"\n /*\n * Convert the multi-byte string to a wide-character string.\n * Remove accents, if wanted. We actually remove all non-word characters.\n * But keep white space.\n */\n wordlen = 0;\n for (s = inword; *s != NUL; )\n {\n\tt = s;\n\tc = mb_cptr2char_adv(&s);\n\tif (slang->sl_rem_accents)\n\t{\n\t if (enc_utf8 ? utf_class(c) == 0 : VIM_ISWHITE(c))\n\t {\n\t\tif (did_white)\n\t\t continue;\n\t\tc = ' ';\n\t\tdid_white = TRUE;\n\t }\n\t else\n\t {\n\t\tdid_white = FALSE;\n\t\tif (!spell_iswordp_nmw(t, curwin))\n\t\t continue;\n\t }\n\t}\n\tword[wordlen++] = c;\n }\n word[wordlen] = NUL;",
" /*\n * This algorithm comes from Aspell phonet.cpp.\n * Converted from C++ to C. Added support for multi-byte chars.\n * Changed to keep spaces.\n */\n i = reslen = z = 0;\n while ((c = word[i]) != NUL)\n {\n\t// Start with the first rule that has the character in the word.\n\tn = slang->sl_sal_first[c & 0xff];\n\tz0 = 0;",
"\tif (n >= 0)\n\t{\n\t // Check all rules for the same index byte.\n\t // If c is 0x300 need extra check for the end of the array, as\n\t // (c & 0xff) is NUL.\n\t for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff)\n\t\t\t\t\t\t\t && ws[0] != NUL; ++n)\n\t {\n\t\t// Quickly skip entries that don't match the word. Most\n\t\t// entries are less than three chars, optimize for that.\n\t\tif (c != ws[0])\n\t\t continue;\n\t\tk = smp[n].sm_leadlen;\n\t\tif (k > 1)\n\t\t{\n\t\t if (word[i + 1] != ws[1])\n\t\t\tcontinue;\n\t\t if (k > 2)\n\t\t {\n\t\t\tfor (j = 2; j < k; ++j)\n\t\t\t if (word[i + j] != ws[j])\n\t\t\t\tbreak;\n\t\t\tif (j < k)\n\t\t\t continue;\n\t\t }\n\t\t}",
"\t\tif ((pf = smp[n].sm_oneof_w) != NULL)\n\t\t{\n\t\t // Check for match with one of the chars in \"sm_oneof\".\n\t\t while (*pf != NUL && *pf != word[i + k])\n\t\t\t++pf;\n\t\t if (*pf == NUL)\n\t\t\tcontinue;\n\t\t ++k;\n\t\t}\n\t\ts = smp[n].sm_rules;\n\t\tpri = 5; // default priority",
"\t\tp0 = *s;\n\t\tk0 = k;\n\t\twhile (*s == '-' && k > 1)\n\t\t{\n\t\t k--;\n\t\t s++;\n\t\t}\n\t\tif (*s == '<')\n\t\t s++;\n\t\tif (VIM_ISDIGIT(*s))\n\t\t{\n\t\t // determine priority\n\t\t pri = *s - '0';\n\t\t s++;\n\t\t}\n\t\tif (*s == '^' && *(s + 1) == '^')\n\t\t s++;",
"\t\tif (*s == NUL\n\t\t\t|| (*s == '^'\n\t\t\t && (i == 0 || !(word[i - 1] == ' '\n\t\t\t\t || spell_iswordp_w(word + i - 1, curwin)))\n\t\t\t && (*(s + 1) != '$'\n\t\t\t\t|| (!spell_iswordp_w(word + i + k0, curwin))))\n\t\t\t|| (*s == '$' && i > 0\n\t\t\t && spell_iswordp_w(word + i - 1, curwin)\n\t\t\t && (!spell_iswordp_w(word + i + k0, curwin))))\n\t\t{\n\t\t // search for followup rules, if:\n\t\t // followup and k > 1 and NO '-' in searchstring\n\t\t c0 = word[i + k - 1];\n\t\t n0 = slang->sl_sal_first[c0 & 0xff];",
"\t\t if (slang->sl_followup && k > 1 && n0 >= 0\n\t\t\t\t\t && p0 != '-' && word[i + k] != NUL)\n\t\t {\n\t\t\t// Test follow-up rule for \"word[i + k]\"; loop over\n\t\t\t// all entries with the same index byte.\n\t\t\tfor ( ; ((ws = smp[n0].sm_lead_w)[0] & 0xff)\n\t\t\t\t\t\t\t == (c0 & 0xff); ++n0)\n\t\t\t{\n\t\t\t // Quickly skip entries that don't match the word.\n\t\t\t if (c0 != ws[0])\n\t\t\t\tcontinue;\n\t\t\t k0 = smp[n0].sm_leadlen;\n\t\t\t if (k0 > 1)\n\t\t\t {\n\t\t\t\tif (word[i + k] != ws[1])\n\t\t\t\t continue;\n\t\t\t\tif (k0 > 2)\n\t\t\t\t{\n\t\t\t\t pf = word + i + k + 1;\n\t\t\t\t for (j = 2; j < k0; ++j)\n\t\t\t\t\tif (*pf++ != ws[j])\n\t\t\t\t\t break;\n\t\t\t\t if (j < k0)\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t }\n\t\t\t k0 += k - 1;",
"\t\t\t if ((pf = smp[n0].sm_oneof_w) != NULL)\n\t\t\t {\n\t\t\t\t// Check for match with one of the chars in\n\t\t\t\t// \"sm_oneof\".\n\t\t\t\twhile (*pf != NUL && *pf != word[i + k0])\n\t\t\t\t ++pf;\n\t\t\t\tif (*pf == NUL)\n\t\t\t\t continue;\n\t\t\t\t++k0;\n\t\t\t }",
"\t\t\t p0 = 5;\n\t\t\t s = smp[n0].sm_rules;\n\t\t\t while (*s == '-')\n\t\t\t {\n\t\t\t\t// \"k0\" gets NOT reduced because\n\t\t\t\t// \"if (k0 == k)\"\n\t\t\t\ts++;\n\t\t\t }\n\t\t\t if (*s == '<')\n\t\t\t\ts++;\n\t\t\t if (VIM_ISDIGIT(*s))\n\t\t\t {\n\t\t\t\tp0 = *s - '0';\n\t\t\t\ts++;\n\t\t\t }",
"\t\t\t if (*s == NUL\n\t\t\t\t // *s == '^' cuts\n\t\t\t\t || (*s == '$'\n\t\t\t\t\t && !spell_iswordp_w(word + i + k0,\n\t\t\t\t\t\t\t\t curwin)))\n\t\t\t {\n\t\t\t\tif (k0 == k)\n\t\t\t\t // this is just a piece of the string\n\t\t\t\t continue;",
"\t\t\t\tif (p0 < pri)\n\t\t\t\t // priority too low\n\t\t\t\t continue;\n\t\t\t\t// rule fits; stop search\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}",
"\t\t\tif (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff)\n\t\t\t\t\t\t\t == (c0 & 0xff))\n\t\t\t continue;\n\t\t }",
"\t\t // replace string\n\t\t ws = smp[n].sm_to_w;\n\t\t s = smp[n].sm_rules;\n\t\t p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0;\n\t\t if (p0 == 1 && z == 0)\n\t\t {\n\t\t\t// rule with '<' is used\n\t\t\tif (reslen > 0 && ws != NULL && *ws != NUL\n\t\t\t\t&& (wres[reslen - 1] == c\n\t\t\t\t\t\t || wres[reslen - 1] == *ws))\n\t\t\t reslen--;\n\t\t\tz0 = 1;\n\t\t\tz = 1;\n\t\t\tk0 = 0;\n\t\t\tif (ws != NULL)\n\t\t\t while (*ws != NUL && word[i + k0] != NUL)\n\t\t\t {\n\t\t\t\tword[i + k0] = *ws;\n\t\t\t\tk0++;\n\t\t\t\tws++;\n\t\t\t }\n\t\t\tif (k > k0)\n\t\t\t mch_memmove(word + i + k0, word + i + k,\n\t\t\t\t sizeof(int) * (wordlen - (i + k) + 1));",
"\t\t\t// new \"actual letter\"\n\t\t\tc = word[i];\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// no '<' rule used\n\t\t\ti += k - 1;\n\t\t\tz = 0;\n\t\t\tif (ws != NULL)\n\t\t\t while (*ws != NUL && ws[1] != NUL\n\t\t\t\t\t\t\t && reslen < MAXWLEN)\n\t\t\t {\n\t\t\t\tif (reslen == 0 || wres[reslen - 1] != *ws)\n\t\t\t\t wres[reslen++] = *ws;\n\t\t\t\tws++;\n\t\t\t }\n\t\t\t// new \"actual letter\"\n\t\t\tif (ws == NULL)\n\t\t\t c = NUL;\n\t\t\telse\n\t\t\t c = *ws;\n\t\t\tif (strstr((char *)s, \"^^\") != NULL)\n\t\t\t{\n\t\t\t if (c != NUL)\n\t\t\t\twres[reslen++] = c;\n\t\t\t mch_memmove(word, word + i + 1,\n\t\t\t\t sizeof(int) * (wordlen - (i + 1) + 1));\n\t\t\t i = 0;\n\t\t\t z0 = 1;\n\t\t\t}\n\t\t }\n\t\t break;\n\t\t}\n\t }\n\t}\n\telse if (VIM_ISWHITE(c))\n\t{\n\t c = ' ';\n\t k = 1;\n\t}",
"\tif (z0 == 0)\n\t{\n\t if (k && !p0 && reslen < MAXWLEN && c != NUL\n\t\t && (!slang->sl_collapse || reslen == 0\n\t\t\t\t\t\t || wres[reslen - 1] != c))\n\t\t// condense only double letters\n\t\twres[reslen++] = c;",
"\t i++;\n\t z = 0;\n\t k = 0;\n\t}\n }",
" // Convert wide characters in \"wres\" to a multi-byte string in \"res\".\n l = 0;\n for (n = 0; n < reslen; ++n)\n {\n\tl += mb_char2bytes(wres[n], res + l);\n\tif (l + MB_MAXBYTES > MAXWLEN)\n\t break;\n }\n res[l] = NUL;\n}",
"/*\n * \":spellinfo\"\n */\n void\nex_spellinfo(exarg_T *eap UNUSED)\n{\n int\t\tlpi;\n langp_T\t*lp;\n char_u\t*p;",
" if (no_spell_checking(curwin))\n\treturn;",
" msg_start();\n for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len && !got_int; ++lpi)\n {\n\tlp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\tmsg_puts(\"file: \");\n\tmsg_puts((char *)lp->lp_slang->sl_fname);\n\tmsg_putchar('\\n');\n\tp = lp->lp_slang->sl_info;\n\tif (p != NULL)\n\t{\n\t msg_puts((char *)p);\n\t msg_putchar('\\n');\n\t}\n }\n msg_end();\n}",
"#define DUMPFLAG_KEEPCASE 1\t// round 2: keep-case tree\n#define DUMPFLAG_COUNT\t 2\t// include word count\n#define DUMPFLAG_ICASE\t 4\t// ignore case when finding matches\n#define DUMPFLAG_ONECAP\t 8\t// pattern starts with capital\n#define DUMPFLAG_ALLCAP\t 16\t// pattern is all capitals",
"/*\n * \":spelldump\"\n */\n void\nex_spelldump(exarg_T *eap)\n{\n char_u *spl;\n long dummy;",
" if (no_spell_checking(curwin))\n\treturn;\n (void)get_option_value((char_u*)\"spl\", &dummy, &spl, NULL, OPT_LOCAL);",
" // Create a new empty buffer in a new window.\n do_cmdline_cmd((char_u *)\"new\");",
" // enable spelling locally in the new window\n set_option_value_give_err((char_u*)\"spell\", TRUE, (char_u*)\"\", OPT_LOCAL);\n set_option_value_give_err((char_u*)\"spl\", dummy, spl, OPT_LOCAL);\n vim_free(spl);",
" if (!BUFEMPTY())\n\treturn;",
" spell_dump_compl(NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0);",
" // Delete the empty line that we started with.\n if (curbuf->b_ml.ml_line_count > 1)\n\tml_delete(curbuf->b_ml.ml_line_count);",
" redraw_later(NOT_VALID);\n}",
"/*\n * Go through all possible words and:\n * 1. When \"pat\" is NULL: dump a list of all words in the current buffer.\n *\t\"ic\" and \"dir\" are not used.\n * 2. When \"pat\" is not NULL: add matching words to insert mode completion.\n */\n void\nspell_dump_compl(\n char_u\t*pat,\t // leading part of the word\n int\t\tic,\t // ignore case\n int\t\t*dir,\t // direction for adding matches\n int\t\tdumpflags_arg)\t// DUMPFLAG_*\n{\n langp_T\t*lp;\n slang_T\t*slang;\n idx_T\tarridx[MAXWLEN];\n int\t\tcuri[MAXWLEN];\n char_u\tword[MAXWLEN];\n int\t\tc;\n char_u\t*byts;\n idx_T\t*idxs;\n linenr_T\tlnum = 0;\n int\t\tround;\n int\t\tdepth;\n int\t\tn;\n int\t\tflags;\n char_u\t*region_names = NULL;\t // region names being used\n int\t\tdo_region = TRUE;\t // dump region names and numbers\n char_u\t*p;\n int\t\tlpi;\n int\t\tdumpflags = dumpflags_arg;\n int\t\tpatlen;",
" // When ignoring case or when the pattern starts with capital pass this on\n // to dump_word().\n if (pat != NULL)\n {\n\tif (ic)\n\t dumpflags |= DUMPFLAG_ICASE;\n\telse\n\t{\n\t n = captype(pat, NULL);\n\t if (n == WF_ONECAP)\n\t\tdumpflags |= DUMPFLAG_ONECAP;\n\t else if (n == WF_ALLCAP && (int)STRLEN(pat) > mb_ptr2len(pat))\n\t\tdumpflags |= DUMPFLAG_ALLCAP;\n\t}\n }",
" // Find out if we can support regions: All languages must support the same\n // regions or none at all.\n for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)\n {\n\tlp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\tp = lp->lp_slang->sl_regions;\n\tif (p[0] != 0)\n\t{\n\t if (region_names == NULL)\t // first language with regions\n\t\tregion_names = p;\n\t else if (STRCMP(region_names, p) != 0)\n\t {\n\t\tdo_region = FALSE;\t // region names are different\n\t\tbreak;\n\t }\n\t}\n }",
" if (do_region && region_names != NULL)\n {\n\tif (pat == NULL)\n\t{\n\t vim_snprintf((char *)IObuff, IOSIZE, \"/regions=%s\", region_names);\n\t ml_append(lnum++, IObuff, (colnr_T)0, FALSE);\n\t}\n }\n else\n\tdo_region = FALSE;",
" /*\n * Loop over all files loaded for the entries in 'spelllang'.\n */\n for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)\n {\n\tlp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);\n\tslang = lp->lp_slang;\n\tif (slang->sl_fbyts == NULL)\t // reloading failed\n\t continue;",
"\tif (pat == NULL)\n\t{\n\t vim_snprintf((char *)IObuff, IOSIZE, \"# file: %s\", slang->sl_fname);\n\t ml_append(lnum++, IObuff, (colnr_T)0, FALSE);\n\t}",
"\t// When matching with a pattern and there are no prefixes only use\n\t// parts of the tree that match \"pat\".\n\tif (pat != NULL && slang->sl_pbyts == NULL)\n\t patlen = (int)STRLEN(pat);\n\telse\n\t patlen = -1;",
"\t// round 1: case-folded tree\n\t// round 2: keep-case tree\n\tfor (round = 1; round <= 2; ++round)\n\t{\n\t if (round == 1)\n\t {\n\t\tdumpflags &= ~DUMPFLAG_KEEPCASE;\n\t\tbyts = slang->sl_fbyts;\n\t\tidxs = slang->sl_fidxs;\n\t }\n\t else\n\t {\n\t\tdumpflags |= DUMPFLAG_KEEPCASE;\n\t\tbyts = slang->sl_kbyts;\n\t\tidxs = slang->sl_kidxs;\n\t }\n\t if (byts == NULL)\n\t\tcontinue;\t\t// array is empty",
"\t depth = 0;\n\t arridx[0] = 0;\n\t curi[0] = 1;\n\t while (depth >= 0 && !got_int\n\t\t\t\t && (pat == NULL || !ins_compl_interrupted()))\n\t {\n\t\tif (curi[depth] > byts[arridx[depth]])\n\t\t{\n\t\t // Done all bytes at this node, go up one level.\n\t\t --depth;\n\t\t line_breakcheck();\n\t\t ins_compl_check_keys(50, FALSE);\n\t\t}\n\t\telse\n\t\t{\n\t\t // Do one more byte at this node.\n\t\t n = arridx[depth] + curi[depth];\n\t\t ++curi[depth];\n\t\t c = byts[n];\n\t\t if (c == 0)\n\t\t {\n\t\t\t// End of word, deal with the word.\n\t\t\t// Don't use keep-case words in the fold-case tree,\n\t\t\t// they will appear in the keep-case tree.\n\t\t\t// Only use the word when the region matches.\n\t\t\tflags = (int)idxs[n];\n\t\t\tif ((round == 2 || (flags & WF_KEEPCAP) == 0)\n\t\t\t\t&& (flags & WF_NEEDCOMP) == 0\n\t\t\t\t&& (do_region\n\t\t\t\t || (flags & WF_REGION) == 0\n\t\t\t\t || (((unsigned)flags >> 16)\n\t\t\t\t\t\t & lp->lp_region) != 0))\n\t\t\t{\n\t\t\t word[depth] = NUL;\n\t\t\t if (!do_region)\n\t\t\t\tflags &= ~WF_REGION;",
"\t\t\t // Dump the basic word if there is no prefix or\n\t\t\t // when it's the first one.\n\t\t\t c = (unsigned)flags >> 24;\n\t\t\t if (c == 0 || curi[depth] == 2)\n\t\t\t {\n\t\t\t\tdump_word(slang, word, pat, dir,\n\t\t\t\t\t\t dumpflags, flags, lnum);\n\t\t\t\tif (pat == NULL)\n\t\t\t\t ++lnum;\n\t\t\t }",
"\t\t\t // Apply the prefix, if there is one.\n\t\t\t if (c != 0)\n\t\t\t\tlnum = dump_prefixes(slang, word, pat, dir,\n\t\t\t\t\t\t dumpflags, flags, lnum);\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// Normal char, go one level deeper.\n\t\t\tword[depth++] = c;\n\t\t\tarridx[depth] = idxs[n];\n\t\t\tcuri[depth] = 1;",
"\t\t\t// Check if this character matches with the pattern.\n\t\t\t// If not skip the whole tree below it.\n\t\t\t// Always ignore case here, dump_word() will check\n\t\t\t// proper case later. This isn't exactly right when\n\t\t\t// length changes for multi-byte characters with\n\t\t\t// ignore case...\n\t\t\tif (depth <= patlen\n\t\t\t\t\t&& MB_STRNICMP(word, pat, depth) != 0)\n\t\t\t --depth;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n}",
"/*\n * Dump one word: apply case modifications and append a line to the buffer.\n * When \"lnum\" is zero add insert mode completion.\n */\n static void\ndump_word(\n slang_T\t*slang,\n char_u\t*word,\n char_u\t*pat,\n int\t\t*dir,\n int\t\tdumpflags,\n int\t\twordflags,\n linenr_T\tlnum)\n{\n int\t\tkeepcap = FALSE;\n char_u\t*p;\n char_u\t*tw;\n char_u\tcword[MAXWLEN];\n char_u\tbadword[MAXWLEN + 10];\n int\t\ti;\n int\t\tflags = wordflags;",
" if (dumpflags & DUMPFLAG_ONECAP)\n\tflags |= WF_ONECAP;\n if (dumpflags & DUMPFLAG_ALLCAP)\n\tflags |= WF_ALLCAP;",
" if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0)\n {\n\t// Need to fix case according to \"flags\".\n\tmake_case_word(word, cword, flags);\n\tp = cword;\n }\n else\n {\n\tp = word;\n\tif ((dumpflags & DUMPFLAG_KEEPCASE)\n\t\t&& ((captype(word, NULL) & WF_KEEPCAP) == 0\n\t\t\t\t\t\t || (flags & WF_FIXCAP) != 0))\n\t keepcap = TRUE;\n }\n tw = p;",
" if (pat == NULL)\n {\n\t// Add flags and regions after a slash.\n\tif ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap)\n\t{\n\t STRCPY(badword, p);\n\t STRCAT(badword, \"/\");\n\t if (keepcap)\n\t\tSTRCAT(badword, \"=\");\n\t if (flags & WF_BANNED)\n\t\tSTRCAT(badword, \"!\");\n\t else if (flags & WF_RARE)\n\t\tSTRCAT(badword, \"?\");\n\t if (flags & WF_REGION)\n\t\tfor (i = 0; i < 7; ++i)\n\t\t if (flags & (0x10000 << i))\n\t\t\tsprintf((char *)badword + STRLEN(badword), \"%d\", i + 1);\n\t p = badword;\n\t}",
"\tif (dumpflags & DUMPFLAG_COUNT)\n\t{\n\t hashitem_T *hi;",
"\t // Include the word count for \":spelldump!\".\n\t hi = hash_find(&slang->sl_wordcount, tw);\n\t if (!HASHITEM_EMPTY(hi))\n\t {\n\t\tvim_snprintf((char *)IObuff, IOSIZE, \"%s\\t%d\",\n\t\t\t\t\t\t tw, HI2WC(hi)->wc_count);\n\t\tp = IObuff;\n\t }\n\t}",
"\tml_append(lnum, p, (colnr_T)0, FALSE);\n }\n else if (((dumpflags & DUMPFLAG_ICASE)\n\t\t ? MB_STRNICMP(p, pat, STRLEN(pat)) == 0\n\t\t : STRNCMP(p, pat, STRLEN(pat)) == 0)\n\t\t&& ins_compl_add_infercase(p, (int)STRLEN(p),\n\t\t\t\t\t p_ic, NULL, *dir, FALSE) == OK)\n\t// if dir was BACKWARD then honor it just once\n\t*dir = FORWARD;\n}",
"/*\n * For \":spelldump\": Find matching prefixes for \"word\". Prepend each to\n * \"word\" and append a line to the buffer.\n * When \"lnum\" is zero add insert mode completion.\n * Return the updated line number.\n */\n static linenr_T\ndump_prefixes(\n slang_T\t*slang,\n char_u\t*word,\t // case-folded word\n char_u\t*pat,\n int\t\t*dir,\n int\t\tdumpflags,\n int\t\tflags,\t // flags with prefix ID\n linenr_T\tstartlnum)\n{\n idx_T\tarridx[MAXWLEN];\n int\t\tcuri[MAXWLEN];\n char_u\tprefix[MAXWLEN];\n char_u\tword_up[MAXWLEN];\n int\t\thas_word_up = FALSE;\n int\t\tc;\n char_u\t*byts;\n idx_T\t*idxs;\n linenr_T\tlnum = startlnum;\n int\t\tdepth;\n int\t\tn;\n int\t\tlen;\n int\t\ti;",
" // If the word starts with a lower-case letter make the word with an\n // upper-case letter in word_up[].\n c = PTR2CHAR(word);\n if (SPELL_TOUPPER(c) != c)\n {\n\tonecap_copy(word, word_up, TRUE);\n\thas_word_up = TRUE;\n }",
" byts = slang->sl_pbyts;\n idxs = slang->sl_pidxs;\n if (byts != NULL)\t\t// array not is empty\n {\n\t/*\n\t * Loop over all prefixes, building them byte-by-byte in prefix[].\n\t * When at the end of a prefix check that it supports \"flags\".\n\t */\n\tdepth = 0;\n\tarridx[0] = 0;\n\tcuri[0] = 1;\n\twhile (depth >= 0 && !got_int)\n\t{\n\t n = arridx[depth];\n\t len = byts[n];\n\t if (curi[depth] > len)\n\t {\n\t\t// Done all bytes at this node, go up one level.\n\t\t--depth;\n\t\tline_breakcheck();\n\t }\n\t else\n\t {\n\t\t// Do one more byte at this node.\n\t\tn += curi[depth];\n\t\t++curi[depth];\n\t\tc = byts[n];\n\t\tif (c == 0)\n\t\t{\n\t\t // End of prefix, find out how many IDs there are.\n\t\t for (i = 1; i < len; ++i)\n\t\t\tif (byts[n + i] != 0)\n\t\t\t break;\n\t\t curi[depth] += i - 1;",
"\t\t c = valid_word_prefix(i, n, flags, word, slang, FALSE);\n\t\t if (c != 0)\n\t\t {\n\t\t\tvim_strncpy(prefix + depth, word, MAXWLEN - depth - 1);\n\t\t\tdump_word(slang, prefix, pat, dir, dumpflags,\n\t\t\t\t(c & WF_RAREPFX) ? (flags | WF_RARE)\n\t\t\t\t\t\t\t : flags, lnum);\n\t\t\tif (lnum != 0)\n\t\t\t ++lnum;\n\t\t }",
"\t\t // Check for prefix that matches the word when the\n\t\t // first letter is upper-case, but only if the prefix has\n\t\t // a condition.\n\t\t if (has_word_up)\n\t\t {\n\t\t\tc = valid_word_prefix(i, n, flags, word_up, slang,\n\t\t\t\t\t\t\t\t\tTRUE);\n\t\t\tif (c != 0)\n\t\t\t{\n\t\t\t vim_strncpy(prefix + depth, word_up,\n\t\t\t\t\t\t\t MAXWLEN - depth - 1);\n\t\t\t dump_word(slang, prefix, pat, dir, dumpflags,\n\t\t\t\t (c & WF_RAREPFX) ? (flags | WF_RARE)\n\t\t\t\t\t\t\t : flags, lnum);\n\t\t\t if (lnum != 0)\n\t\t\t\t++lnum;\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t\t // Normal char, go one level deeper.\n\t\t prefix[depth++] = c;\n\t\t arridx[depth] = idxs[n];\n\t\t curi[depth] = 1;\n\t\t}\n\t }\n\t}\n }",
" return lnum;\n}",
"/*\n * Move \"p\" to the end of word \"start\".\n * Uses the spell-checking word characters.\n */\n char_u *\nspell_to_word_end(char_u *start, win_T *win)\n{\n char_u *p = start;",
" while (*p != NUL && spell_iswordp(p, win))\n\tMB_PTR_ADV(p);\n return p;\n}",
"/*\n * For Insert mode completion CTRL-X s:\n * Find start of the word in front of column \"startcol\".\n * We don't check if it is badly spelled, with completion we can only change\n * the word in front of the cursor.\n * Returns the column number of the word.\n */\n int\nspell_word_start(int startcol)\n{\n char_u\t*line;\n char_u\t*p;\n int\t\tcol = 0;",
" if (no_spell_checking(curwin))\n\treturn startcol;",
" // Find a word character before \"startcol\".\n line = ml_get_curline();\n for (p = line + startcol; p > line; )\n {\n\tMB_PTR_BACK(line, p);\n\tif (spell_iswordp_nmw(p, curwin))\n\t break;\n }",
" // Go back to start of the word.\n while (p > line)\n {\n\tcol = (int)(p - line);\n\tMB_PTR_BACK(line, p);\n\tif (!spell_iswordp(p, curwin))\n\t break;\n\tcol = 0;\n }",
" return col;\n}",
"/*\n * Need to check for 'spellcapcheck' now, the word is removed before\n * expand_spelling() is called. Therefore the ugly global variable.\n */\nstatic int spell_expand_need_cap;",
" void\nspell_expand_check_cap(colnr_T col)\n{\n spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col);\n}",
"/*\n * Get list of spelling suggestions.\n * Used for Insert mode completion CTRL-X ?.\n * Returns the number of matches. The matches are in \"matchp[]\", array of\n * allocated strings.\n */\n int\nexpand_spelling(\n linenr_T\tlnum UNUSED,\n char_u\t*pat,\n char_u\t***matchp)\n{\n garray_T\tga;",
" spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, TRUE);\n *matchp = ga.ga_data;\n return ga.ga_len;\n}",
"/*\n * Return TRUE if \"val\" is a valid 'spelllang' value.\n */\n int\nvalid_spelllang(char_u *val)\n{\n return valid_name(val, \".-_,@\");\n}",
"/*\n * Return TRUE if \"val\" is a valid 'spellfile' value.\n */\n int\nvalid_spellfile(char_u *val)\n{\n char_u *s;",
" for (s = val; *s != NUL; ++s)\n\tif (!vim_isfilec(*s) && *s != ',' && *s != ' ')\n\t return FALSE;\n return TRUE;\n}",
"/*\n * Handle side effects of setting 'spell'.\n * Return an error message or NULL for success.\n */\n char *\ndid_set_spell_option(int is_spellfile)\n{\n char *errmsg = NULL;\n win_T *wp;\n int\t l;",
" if (is_spellfile)\n {\n\tl = (int)STRLEN(curwin->w_s->b_p_spf);\n\tif (l > 0 && (l < 4\n\t\t\t|| STRCMP(curwin->w_s->b_p_spf + l - 4, \".add\") != 0))\n\t errmsg = e_invalid_argument;\n }",
" if (errmsg == NULL)\n {\n\tFOR_ALL_WINDOWS(wp)\n\t if (wp->w_buffer == curbuf && wp->w_p_spell)\n\t {\n\t\terrmsg = did_set_spelllang(wp);\n\t\tbreak;\n\t }\n }\n return errmsg;\n}",
"/*\n * Set curbuf->b_cap_prog to the regexp program for 'spellcapcheck'.\n * Return error message when failed, NULL when OK.\n */\n char *\ncompile_cap_prog(synblock_T *synblock)\n{\n regprog_T *rp = synblock->b_cap_prog;\n char_u\t*re;",
" if (synblock->b_p_spc == NULL || *synblock->b_p_spc == NUL)\n\tsynblock->b_cap_prog = NULL;\n else\n {\n\t// Prepend a ^ so that we only match at one column\n\tre = concat_str((char_u *)\"^\", synblock->b_p_spc);\n\tif (re != NULL)\n\t{\n\t synblock->b_cap_prog = vim_regcomp(re, RE_MAGIC);\n\t vim_free(re);\n\t if (synblock->b_cap_prog == NULL)\n\t {\n\t\tsynblock->b_cap_prog = rp; // restore the previous program\n\t\treturn e_invalid_argument;\n\t }\n\t}\n }",
" vim_regfree(rp);\n return NULL;\n}",
"#endif // FEAT_SPELL"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [1491, 804, 736], "buggy_code_start_loc": [1278, 804, 736], "filenames": ["src/spell.c", "src/testdir/test_spell_utf8.vim", "src/version.c"], "fixing_code_end_loc": [1495, 820, 739], "fixing_code_start_loc": [1278, 805, 737], "message": "Use After Free in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B6CDC65-37D1-4A6A-B6C5-7B58DC5757ED", "versionEndExcluding": "8.2.5072", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "0146DEE5-EF72-48C3-9DDD-28EA3595BDD1", "versionEndExcluding": "11.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7B7BC361-3A04-4C88-A3AE-82B9993A73A0", "versionEndExcluding": "12.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use After Free in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Un Uso de Memoria Previamente Liberada en el repositorio GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2042", "lastModified": "2023-05-03T12:15:40.820", "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": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 0.8, "impactScore": 6.0, "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-06-10T19:15:08.813", "references": [{"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/28"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/41"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/43"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/45"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/8628b4cd-4055-4059-aed4-64f7fdc10eba"}, {"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"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213443"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213444"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213488"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, "type": "CWE-416"}
| 317
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"\" Test for spell checking with 'encoding' set to utf-8",
"source check.vim\nCheckFeature spell",
"scriptencoding utf-8",
"func TearDown()\n set nospell\n call delete('Xtest.aff')\n call delete('Xtest.dic')\n call delete('Xtest.utf-8.add')\n call delete('Xtest.utf-8.add.spl')\n call delete('Xtest.utf-8.spl')\n call delete('Xtest.utf-8.sug')\nendfunc",
"let g:test_data_aff1 = [\n \\\"SET ISO8859-1\",\n \\\"TRY esianrtolcdugmphbyfvkwjkqxz-ëéèêïîäàâöüû'ESIANRTOLCDUGMPHBYFVKWJKQXZ\",\n \\\"\",\n \\\"FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ\",\n \\\"LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ\",\n \\\"UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ\",\n \\\"\",\n \\\"SOFOFROM abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xBF\",\n \\\"SOFOTO ebctefghejklnnepkrstevvkesebctefghejklnnepkrstevvkeseeeeeeeceeeeeeeedneeeeeeeeeeepseeeeeeeeceeeeeeeedneeeeeeeeeeep?\",\n \\\"\",\n \\\"MIDWORD\\t'-\",\n \\\"\",\n \\\"KEP =\",\n \\\"RAR ?\",\n \\\"BAD !\",\n \\\"\",\n \\\"PFX I N 1\",\n \\\"PFX I 0 in .\",\n \\\"\",\n \\\"PFX O Y 1\",\n \\\"PFX O 0 out .\",\n \\\"\",\n \\\"SFX S Y 2\",\n \\\"SFX S 0 s [^s]\",\n \\\"SFX S 0 es s\",\n \\\"\",\n \\\"SFX N N 3\",\n \\\"SFX N 0 en [^n]\",\n \\\"SFX N 0 nen n\",\n \\\"SFX N 0 n .\",\n \\\"\",\n \\\"REP 3\",\n \\\"REP g ch\",\n \\\"REP ch g\",\n \\\"REP svp s.v.p.\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\"\n \\ ]\nlet g:test_data_dic1 = [\n \\\"123456\",\n \\\"test/NO\",\n \\\"# comment\",\n \\\"wrong\",\n \\\"Comment\",\n \\\"OK\",\n \\\"uk\",\n \\\"put/ISO\",\n \\\"the end\",\n \\\"deol\",\n \\\"d\\xE9\\xF4r\",\n \\ ]\nlet g:test_data_aff2 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FOL \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"LOW \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"UPP \\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xFF\",\n \\\"\",\n \\\"PFXPOSTPONE\",\n \\\"\",\n \\\"MIDWORD\\t'-\",\n \\\"\",\n \\\"KEP =\",\n \\\"RAR ?\",\n \\\"BAD !\",\n \\\"\",\n \\\"PFX I N 1\",\n \\\"PFX I 0 in .\",\n \\\"\",\n \\\"PFX O Y 1\",\n \\\"PFX O 0 out [a-z]\",\n \\\"\",\n \\\"SFX S Y 2\",\n \\\"SFX S 0 s [^s]\",\n \\\"SFX S 0 es s\",\n \\\"\",\n \\\"SFX N N 3\",\n \\\"SFX N 0 en [^n]\",\n \\\"SFX N 0 nen n\",\n \\\"SFX N 0 n .\",\n \\\"\",\n \\\"REP 3\",\n \\\"REP g ch\",\n \\\"REP ch g\",\n \\\"REP svp s.v.p.\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\",\n \\ ]\nlet g:test_data_aff3 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"COMPOUNDMIN 3\",\n \\\"COMPOUNDRULE m*\",\n \\\"NEEDCOMPOUND x\",\n \\ ]\nlet g:test_data_dic3 = [\n \\\"1234\",\n \\\"foo/m\",\n \\\"bar/mx\",\n \\\"m\\xEF/m\",\n \\\"la/mx\",\n \\ ]\nlet g:test_data_aff4 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FOL \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"LOW \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"UPP \\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xFF\",\n \\\"\",\n \\\"COMPOUNDRULE m+\",\n \\\"COMPOUNDRULE sm*e\",\n \\\"COMPOUNDRULE sm+\",\n \\\"COMPOUNDMIN 3\",\n \\\"COMPOUNDWORDMAX 3\",\n \\\"COMPOUNDFORBIDFLAG t\",\n \\\"\",\n \\\"COMPOUNDSYLMAX 5\",\n \\\"SYLLABLE a\\xE1e\\xE9i\\xEDo\\xF3\\xF6\\xF5u\\xFA\\xFC\\xFBy/aa/au/ea/ee/ei/ie/oa/oe/oo/ou/uu/ui\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\",\n \\\"\",\n \\\"NEEDAFFIX x\",\n \\\"\",\n \\\"PFXPOSTPONE\",\n \\\"\",\n \\\"MIDWORD '-\",\n \\\"\",\n \\\"SFX q N 1\",\n \\\"SFX q 0 -ok .\",\n \\\"\",\n \\\"SFX a Y 2\",\n \\\"SFX a 0 s .\",\n \\\"SFX a 0 ize/t .\",\n \\\"\",\n \\\"PFX p N 1\",\n \\\"PFX p 0 pre .\",\n \\\"\",\n \\\"PFX P N 1\",\n \\\"PFX P 0 nou .\",\n \\ ]\nlet g:test_data_dic4 = [\n \\\"1234\",\n \\\"word/mP\",\n \\\"util/am\",\n \\\"pro/xq\",\n \\\"tomato/m\",\n \\\"bork/mp\",\n \\\"start/s\",\n \\\"end/e\",\n \\ ]\nlet g:test_data_aff5 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FLAG long\",\n \\\"\",\n \\\"NEEDAFFIX !!\",\n \\\"\",\n \\\"COMPOUNDRULE ssmm*ee\",\n \\\"\",\n \\\"NEEDCOMPOUND xx\",\n \\\"COMPOUNDPERMITFLAG pp\",\n \\\"\",\n \\\"SFX 13 Y 1\",\n \\\"SFX 13 0 bork .\",\n \\\"\",\n \\\"SFX a1 Y 1\",\n \\\"SFX a1 0 a1 .\",\n \\\"\",\n \\\"SFX a\\xE9 Y 1\",\n \\\"SFX a\\xE9 0 a\\xE9 .\",\n \\\"\",\n \\\"PFX zz Y 1\",\n \\\"PFX zz 0 pre/pp .\",\n \\\"\",\n \\\"PFX yy Y 1\",\n \\\"PFX yy 0 nou .\",\n \\ ]\nlet g:test_data_dic5 = [\n \\\"1234\",\n \\\"foo/a1a\\xE9!!\",\n \\\"bar/zz13ee\",\n \\\"start/ss\",\n \\\"end/eeyy\",\n \\\"middle/mmxx\",\n \\ ]\nlet g:test_data_aff6 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FLAG caplong\",\n \\\"\",\n \\\"NEEDAFFIX A!\",\n \\\"\",\n \\\"COMPOUNDRULE sMm*Ee\",\n \\\"\",\n \\\"NEEDCOMPOUND Xx\",\n \\\"\",\n \\\"COMPOUNDPERMITFLAG p\",\n \\\"\",\n \\\"SFX N3 Y 1\",\n \\\"SFX N3 0 bork .\",\n \\\"\",\n \\\"SFX A1 Y 1\",\n \\\"SFX A1 0 a1 .\",\n \\\"\",\n \\\"SFX A\\xE9 Y 1\",\n \\\"SFX A\\xE9 0 a\\xE9 .\",\n \\\"\",\n \\\"PFX Zz Y 1\",\n \\\"PFX Zz 0 pre/p .\",\n \\ ]\nlet g:test_data_dic6 = [\n \\\"1234\",\n \\\"mee/A1A\\xE9A!\",\n \\\"bar/ZzN3Ee\",\n \\\"lead/s\",\n \\\"end/Ee\",\n \\\"middle/MmXx\",\n \\ ]\nlet g:test_data_aff7 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FLAG num\",\n \\\"\",\n \\\"NEEDAFFIX 9999\",\n \\\"\",\n \\\"COMPOUNDRULE 2,77*123\",\n \\\"\",\n \\\"NEEDCOMPOUND 1\",\n \\\"COMPOUNDPERMITFLAG 432\",\n \\\"\",\n \\\"SFX 61003 Y 1\",\n \\\"SFX 61003 0 meat .\",\n \\\"\",\n \\\"SFX 0 Y 1\",\n \\\"SFX 0 0 zero .\",\n \\\"\",\n \\\"SFX 391 Y 1\",\n \\\"SFX 391 0 a1 .\",\n \\\"\",\n \\\"SFX 111 Y 1\",\n \\\"SFX 111 0 a\\xE9 .\",\n \\\"\",\n \\\"PFX 17 Y 1\",\n \\\"PFX 17 0 pre/432 .\",\n \\ ]\nlet g:test_data_dic7 = [\n \\\"1234\",\n \\\"mee/0,391,111,9999\",\n \\\"bar/17,61003,123\",\n \\\"lead/2\",\n \\\"tail/123\",\n \\\"middle/77,1\",\n \\ ]\nlet g:test_data_aff8 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"NOSPLITSUGS\",\n \\ ]\nlet g:test_data_dic8 = [\n \\\"1234\",\n \\\"foo\",\n \\\"bar\",\n \\\"faabar\",\n \\ ]\nlet g:test_data_aff9 = [\n \\ ]\nlet g:test_data_dic9 = [\n \\\"1234\",\n \\\"foo\",\n \\\"bar\",\n \\ ]\nlet g:test_data_aff10 = [\n \\\"COMPOUNDRULE se\",\n \\\"COMPOUNDPERMITFLAG p\",\n \\\"\",\n \\\"SFX A Y 1\",\n \\\"SFX A 0 able/Mp .\",\n \\\"\",\n \\\"SFX M Y 1\",\n \\\"SFX M 0 s .\",\n \\ ]\nlet g:test_data_dic10 = [\n \\\"1234\",\n \\\"drink/As\",\n \\\"table/e\",\n \\ ]\nlet g:test_data_aff_sal = [\n \\\"SET ISO8859-1\",\n \\\"TRY esianrtolcdugmphbyfvkwjkqxz-\\xEB\\xE9\\xE8\\xEA\\xEF\\xEE\\xE4\\xE0\\xE2\\xF6\\xFC\\xFB'ESIANRTOLCDUGMPHBYFVKWJKQXZ\",\n \\\"\",\n \\\"FOL \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"LOW \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"UPP \\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xFF\",\n \\\"\",\n \\\"MIDWORD\\t'-\",\n \\\"\",\n \\\"KEP =\",\n \\\"RAR ?\",\n \\\"BAD !\",\n \\\"\",\n \\\"PFX I N 1\",\n \\\"PFX I 0 in .\",\n \\\"\",\n \\\"PFX O Y 1\",\n \\\"PFX O 0 out .\",\n \\\"\",\n \\\"SFX S Y 2\",\n \\\"SFX S 0 s [^s]\",\n \\\"SFX S 0 es s\",\n \\\"\",\n \\\"SFX N N 3\",\n \\\"SFX N 0 en [^n]\",\n \\\"SFX N 0 nen n\",\n \\\"SFX N 0 n .\",\n \\\"\",\n \\\"REP 3\",\n \\\"REP g ch\",\n \\\"REP ch g\",\n \\\"REP svp s.v.p.\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\",\n \\\"\",\n \\\"SAL AH(AEIOUY)-^ *H\",\n \\\"SAL AR(AEIOUY)-^ *R\",\n \\\"SAL A(HR)^ *\",\n \\\"SAL A^ *\",\n \\\"SAL AH(AEIOUY)- H\",\n \\\"SAL AR(AEIOUY)- R\",\n \\\"SAL A(HR) _\",\n \\\"SAL \\xC0^ *\",\n \\\"SAL \\xC5^ *\",\n \\\"SAL BB- _\",\n \\\"SAL B B\",\n \\\"SAL CQ- _\",\n \\\"SAL CIA X\",\n \\\"SAL CH X\",\n \\\"SAL C(EIY)- S\",\n \\\"SAL CK K\",\n \\\"SAL COUGH^ KF\",\n \\\"SAL CC< C\",\n \\\"SAL C K\",\n \\\"SAL DG(EIY) K\",\n \\\"SAL DD- _\",\n \\\"SAL D T\",\n \\\"SAL \\xC9< E\",\n \\\"SAL EH(AEIOUY)-^ *H\",\n \\\"SAL ER(AEIOUY)-^ *R\",\n \\\"SAL E(HR)^ *\",\n \\\"SAL ENOUGH^$ *NF\",\n \\\"SAL E^ *\",\n \\\"SAL EH(AEIOUY)- H\",\n \\\"SAL ER(AEIOUY)- R\",\n \\\"SAL E(HR) _\",\n \\\"SAL FF- _\",\n \\\"SAL F F\",\n \\\"SAL GN^ N\",\n \\\"SAL GN$ N\",\n \\\"SAL GNS$ NS\",\n \\\"SAL GNED$ N\",\n \\\"SAL GH(AEIOUY)- K\",\n \\\"SAL GH _\",\n \\\"SAL GG9 K\",\n \\\"SAL G K\",\n \\\"SAL H H\",\n \\\"SAL IH(AEIOUY)-^ *H\",\n \\\"SAL IR(AEIOUY)-^ *R\",\n \\\"SAL I(HR)^ *\",\n \\\"SAL I^ *\",\n \\\"SAL ING6 N\",\n \\\"SAL IH(AEIOUY)- H\",\n \\\"SAL IR(AEIOUY)- R\",\n \\\"SAL I(HR) _\",\n \\\"SAL J K\",\n \\\"SAL KN^ N\",\n \\\"SAL KK- _\",\n \\\"SAL K K\",\n \\\"SAL LAUGH^ LF\",\n \\\"SAL LL- _\",\n \\\"SAL L L\",\n \\\"SAL MB$ M\",\n \\\"SAL MM M\",\n \\\"SAL M M\",\n \\\"SAL NN- _\",\n \\\"SAL N N\",\n \\\"SAL OH(AEIOUY)-^ *H\",\n \\\"SAL OR(AEIOUY)-^ *R\",\n \\\"SAL O(HR)^ *\",\n \\\"SAL O^ *\",\n \\\"SAL OH(AEIOUY)- H\",\n \\\"SAL OR(AEIOUY)- R\",\n \\\"SAL O(HR) _\",\n \\\"SAL PH F\",\n \\\"SAL PN^ N\",\n \\\"SAL PP- _\",\n \\\"SAL P P\",\n \\\"SAL Q K\",\n \\\"SAL RH^ R\",\n \\\"SAL ROUGH^ RF\",\n \\\"SAL RR- _\",\n \\\"SAL R R\",\n \\\"SAL SCH(EOU)- SK\",\n \\\"SAL SC(IEY)- S\",\n \\\"SAL SH X\",\n \\\"SAL SI(AO)- X\",\n \\\"SAL SS- _\",\n \\\"SAL S S\",\n \\\"SAL TI(AO)- X\",\n \\\"SAL TH @\",\n \\\"SAL TCH-- _\",\n \\\"SAL TOUGH^ TF\",\n \\\"SAL TT- _\",\n \\\"SAL T T\",\n \\\"SAL UH(AEIOUY)-^ *H\",\n \\\"SAL UR(AEIOUY)-^ *R\",\n \\\"SAL U(HR)^ *\",\n \\\"SAL U^ *\",\n \\\"SAL UH(AEIOUY)- H\",\n \\\"SAL UR(AEIOUY)- R\",\n \\\"SAL U(HR) _\",\n \\\"SAL V^ W\",\n \\\"SAL V F\",\n \\\"SAL WR^ R\",\n \\\"SAL WH^ W\",\n \\\"SAL W(AEIOU)- W\",\n \\\"SAL X^ S\",\n \\\"SAL X KS\",\n \\\"SAL Y(AEIOU)- Y\",\n \\\"SAL ZZ- _\",\n \\\"SAL Z S\",\n \\ ]",
"func LoadAffAndDic(aff_contents, dic_contents)\n set enc=utf-8\n set spellfile=\n call writefile(a:aff_contents, \"Xtest.aff\")\n call writefile(a:dic_contents, \"Xtest.dic\")\n \" Generate a .spl file from a .dic and .aff file.\n mkspell! Xtest Xtest\n \" use that spell file\n set spl=Xtest.utf-8.spl spell\nendfunc",
"func ListWords()\n spelldump\n %yank\n quit\n return split(@\", \"\\n\")\nendfunc",
"func TestGoodBadBase()\n exe '1;/^good:'\n normal 0f:]s\n let prevbad = ''\n let result = []\n while 1\n let [bad, a] = spellbadword()\n if bad == '' || bad == prevbad || bad == 'badend'\n break\n endif\n let prevbad = bad\n let lst = bad->spellsuggest(3)\n normal mm",
" call add(result, [bad, lst])\n normal `m]s\n endwhile\n return result\nendfunc",
"func RunGoodBad(good, bad, expected_words, expected_bad_words)\n %bwipe!\n call setline(1, ['', \"good: \", a:good, a:bad, \" badend \"])\n let words = ListWords()\n call assert_equal(a:expected_words, words[1:-1])\n let bad_words = TestGoodBadBase()\n call assert_equal(a:expected_bad_words, bad_words)\n %bwipe!\nendfunc",
"func Test_spell_basic()\n call LoadAffAndDic(g:test_data_aff1, g:test_data_dic1)\n call RunGoodBad(\"wrong OK puts. Test the end\",\n \\ \"bad: inputs comment ok Ok. test d\\u00E9\\u00F4l end the\",\n \\[\"Comment\", \"deol\", \"d\\u00E9\\u00F4r\", \"input\", \"OK\", \"output\", \"outputs\", \"outtest\", \"put\", \"puts\",\n \\ \"test\", \"testen\", \"testn\", \"the end\", \"uk\", \"wrong\"],\n \\[\n \\ [\"bad\", [\"put\", \"uk\", \"OK\"]],\n \\ [\"inputs\", [\"input\", \"puts\", \"outputs\"]],\n \\ [\"comment\", [\"Comment\", \"outtest\", \"the end\"]],\n \\ [\"ok\", [\"OK\", \"uk\", \"put\"]],\n \\ [\"Ok\", [\"OK\", \"Uk\", \"Put\"]],\n \\ [\"test\", [\"Test\", \"testn\", \"testen\"]],\n \\ [\"d\\u00E9\\u00F4l\", [\"deol\", \"d\\u00E9\\u00F4r\", \"test\"]],\n \\ [\"end\", [\"put\", \"uk\", \"test\"]],\n \\ [\"the\", [\"put\", \"uk\", \"test\"]],\n \\ ]\n \\ )",
" call assert_equal(\"gebletegek\", soundfold('goobledygoook'))\n call assert_equal(\"kepereneven\", 'kóopërÿnôven'->soundfold())\n call assert_equal(\"everles gesvets etele\", soundfold('oeverloos gezwets edale'))\nendfunc",
"\" Postponed prefixes\nfunc Test_spell_prefixes()\n call LoadAffAndDic(g:test_data_aff2, g:test_data_dic1)\n call RunGoodBad(\"puts\",\n \\ \"bad: inputs comment ok Ok end the. test d\\u00E9\\u00F4l\",\n \\ [\"Comment\", \"deol\", \"d\\u00E9\\u00F4r\", \"OK\", \"put\", \"input\", \"output\", \"puts\", \"outputs\", \"test\", \"outtest\", \"testen\", \"testn\", \"the end\", \"uk\", \"wrong\"],\n \\ [\n \\ [\"bad\", [\"put\", \"uk\", \"OK\"]],\n \\ [\"inputs\", [\"input\", \"puts\", \"outputs\"]],\n \\ [\"comment\", [\"Comment\"]],\n \\ [\"ok\", [\"OK\", \"uk\", \"put\"]],\n \\ [\"Ok\", [\"OK\", \"Uk\", \"Put\"]],\n \\ [\"end\", [\"put\", \"uk\", \"deol\"]],\n \\ [\"the\", [\"put\", \"uk\", \"test\"]],\n \\ [\"test\", [\"Test\", \"testn\", \"testen\"]],\n \\ [\"d\\u00E9\\u00F4l\", [\"deol\", \"d\\u00E9\\u00F4r\", \"test\"]],\n \\ ])\nendfunc",
"\"Compound words\nfunc Test_spell_compound()\n call LoadAffAndDic(g:test_data_aff3, g:test_data_dic3)\n call RunGoodBad(\"foo m\\u00EF foobar foofoobar barfoo barbarfoo\",\n \\ \"bad: bar la foom\\u00EF barm\\u00EF m\\u00EFfoo m\\u00EFbar m\\u00EFm\\u00EF lala m\\u00EFla lam\\u00EF foola labar\",\n \\ [\"foo\", \"m\\u00EF\"],\n \\ [\n \\ [\"bad\", [\"foo\", \"m\\u00EF\"]],\n \\ [\"bar\", [\"barfoo\", \"foobar\", \"foo\"]],\n \\ [\"la\", [\"m\\u00EF\", \"foo\"]],\n \\ [\"foom\\u00EF\", [\"foo m\\u00EF\", \"foo\", \"foofoo\"]],\n \\ [\"barm\\u00EF\", [\"barfoo\", \"m\\u00EF\", \"barbar\"]],\n \\ [\"m\\u00EFfoo\", [\"m\\u00EF foo\", \"foo\", \"foofoo\"]],\n \\ [\"m\\u00EFbar\", [\"foobar\", \"barbar\", \"m\\u00EF\"]],\n \\ [\"m\\u00EFm\\u00EF\", [\"m\\u00EF m\\u00EF\", \"m\\u00EF\"]],\n \\ [\"lala\", []],\n \\ [\"m\\u00EFla\", [\"m\\u00EF\", \"m\\u00EF m\\u00EF\"]],\n \\ [\"lam\\u00EF\", [\"m\\u00EF\", \"m\\u00EF m\\u00EF\"]],\n \\ [\"foola\", [\"foo\", \"foobar\", \"foofoo\"]],\n \\ [\"labar\", [\"barbar\", \"foobar\"]],\n \\ ])",
" call LoadAffAndDic(g:test_data_aff4, g:test_data_dic4)\n call RunGoodBad(\"word util bork prebork start end wordutil wordutils pro-ok bork borkbork borkborkbork borkborkborkbork borkborkborkborkbork tomato tomatotomato startend startword startwordword startwordend startwordwordend startwordwordwordend prebork preborkbork preborkborkbork nouword\",\n \\ \"bad: wordutilize pro borkborkborkborkborkbork tomatotomatotomato endstart endend startstart wordend wordstart preborkprebork preborkpreborkbork startwordwordwordwordend borkpreborkpreborkbork utilsbork startnouword\",\n \\ [\"bork\", \"prebork\", \"end\", \"pro-ok\", \"start\", \"tomato\", \"util\", \"utilize\", \"utils\", \"word\", \"nouword\"],\n \\ [\n \\ [\"bad\", [\"end\", \"bork\", \"word\"]],\n \\ [\"wordutilize\", [\"word utilize\", \"wordutils\", \"wordutil\"]],\n \\ [\"pro\", [\"bork\", \"word\", \"end\"]],\n \\ [\"borkborkborkborkborkbork\", [\"bork borkborkborkborkbork\", \"borkbork borkborkborkbork\", \"borkborkbork borkborkbork\"]],\n \\ [\"tomatotomatotomato\", [\"tomato tomatotomato\", \"tomatotomato tomato\", \"tomato tomato tomato\"]],\n \\ [\"endstart\", [\"end start\", \"start\"]],\n \\ [\"endend\", [\"end end\", \"end\"]],\n \\ [\"startstart\", [\"start start\"]],\n \\ [\"wordend\", [\"word end\", \"word\", \"wordword\"]],\n \\ [\"wordstart\", [\"word start\", \"bork start\"]],\n \\ [\"preborkprebork\", [\"prebork prebork\", \"preborkbork\", \"preborkborkbork\"]],\n \\ [\"preborkpreborkbork\", [\"prebork preborkbork\", \"preborkborkbork\", \"preborkborkborkbork\"]],\n \\ [\"startwordwordwordwordend\", [\"startwordwordwordword end\", \"startwordwordwordword\", \"start wordwordwordword end\"]],\n \\ [\"borkpreborkpreborkbork\", [\"bork preborkpreborkbork\", \"bork prebork preborkbork\", \"bork preborkprebork bork\"]],\n \\ [\"utilsbork\", [\"utilbork\", \"utils bork\", \"util bork\"]],\n \\ [\"startnouword\", [\"start nouword\", \"startword\", \"startborkword\"]],\n \\ ])",
"endfunc",
"\" Test affix flags with two characters\nfunc Test_spell_affix()\n call LoadAffAndDic(g:test_data_aff5, g:test_data_dic5)\n call RunGoodBad(\"fooa1 fooa\\u00E9 bar prebar barbork prebarbork startprebar start end startend startmiddleend nouend\",\n \\ \"bad: foo fooa2 prabar probarbirk middle startmiddle middleend endstart startprobar startnouend\",\n \\ [\"bar\", \"barbork\", \"end\", \"fooa1\", \"fooa\\u00E9\", \"nouend\", \"prebar\", \"prebarbork\", \"start\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"end\", \"fooa1\"]],\n \\ [\"foo\", [\"fooa1\", \"bar\", \"end\"]],\n \\ [\"fooa2\", [\"fooa1\", \"fooa\\u00E9\", \"bar\"]],\n \\ [\"prabar\", [\"prebar\", \"bar\", \"bar bar\"]],\n \\ [\"probarbirk\", [\"prebarbork\"]],\n \\ [\"middle\", []],\n \\ [\"startmiddle\", [\"startmiddleend\", \"startmiddlebar\"]],\n \\ [\"middleend\", []],\n \\ [\"endstart\", [\"end start\", \"start\"]],\n \\ [\"startprobar\", [\"startprebar\", \"start prebar\", \"startbar\"]],\n \\ [\"startnouend\", [\"start nouend\", \"startend\"]],\n \\ ])",
" call LoadAffAndDic(g:test_data_aff6, g:test_data_dic6)\n call RunGoodBad(\"meea1 meea\\u00E9 bar prebar barbork prebarbork leadprebar lead end leadend leadmiddleend\",\n \\ \"bad: mee meea2 prabar probarbirk middle leadmiddle middleend endlead leadprobar\",\n \\ [\"bar\", \"barbork\", \"end\", \"lead\", \"meea1\", \"meea\\u00E9\", \"prebar\", \"prebarbork\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"end\", \"lead\"]],\n \\ [\"mee\", [\"meea1\", \"bar\", \"end\"]],\n \\ [\"meea2\", [\"meea1\", \"meea\\u00E9\", \"lead\"]],\n \\ [\"prabar\", [\"prebar\", \"bar\", \"leadbar\"]],\n \\ [\"probarbirk\", [\"prebarbork\"]],\n \\ [\"middle\", []],\n \\ [\"leadmiddle\", [\"leadmiddleend\", \"leadmiddlebar\"]],\n \\ [\"middleend\", []],\n \\ [\"endlead\", [\"end lead\", \"lead\", \"end end\"]],\n \\ [\"leadprobar\", [\"leadprebar\", \"lead prebar\", \"leadbar\"]],\n \\ ])",
" call LoadAffAndDic(g:test_data_aff7, g:test_data_dic7)\n call RunGoodBad(\"meea1 meezero meea\\u00E9 bar prebar barmeat prebarmeat leadprebar lead tail leadtail leadmiddletail\",\n \\ \"bad: mee meea2 prabar probarmaat middle leadmiddle middletail taillead leadprobar\",\n \\ [\"bar\", \"barmeat\", \"lead\", \"meea1\", \"meea\\u00E9\", \"meezero\", \"prebar\", \"prebarmeat\", \"tail\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"lead\", \"tail\"]],\n \\ [\"mee\", [\"meea1\", \"bar\", \"lead\"]],\n \\ [\"meea2\", [\"meea1\", \"meea\\u00E9\", \"lead\"]],\n \\ [\"prabar\", [\"prebar\", \"bar\", \"leadbar\"]],\n \\ [\"probarmaat\", [\"prebarmeat\"]],\n \\ [\"middle\", []],\n \\ [\"leadmiddle\", [\"leadmiddlebar\"]],\n \\ [\"middletail\", []],\n \\ [\"taillead\", [\"tail lead\", \"tail\"]],\n \\ [\"leadprobar\", [\"leadprebar\", \"lead prebar\", \"leadbar\"]],\n \\ ])\nendfunc",
"func Test_spell_NOSLITSUGS()\n call LoadAffAndDic(g:test_data_aff8, g:test_data_dic8)\n call RunGoodBad(\"foo bar faabar\", \"bad: foobar barfoo\",\n \\ [\"bar\", \"faabar\", \"foo\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"foo\"]],\n \\ [\"foobar\", [\"faabar\", \"foo bar\", \"bar\"]],\n \\ [\"barfoo\", [\"bar foo\", \"bar\", \"foo\"]],\n \\ ])\nendfunc",
"\" Numbers\nfunc Test_spell_Numbers()\n call LoadAffAndDic(g:test_data_aff9, g:test_data_dic9)\n call RunGoodBad(\"0b1011 0777 1234 0x01ff\", \"\",\n \\ [\"bar\", \"foo\"],\n \\ [\n \\ ])\nendfunc",
"\" Affix flags\nfunc Test_spell_affix_flags()\n call LoadAffAndDic(g:test_data_aff10, g:test_data_dic10)\n call RunGoodBad(\"drink drinkable drinkables drinktable drinkabletable\",\n\t\\ \"bad: drinks drinkstable drinkablestable\",\n \\ [\"drink\", \"drinkable\", \"drinkables\", \"table\"],\n \\ [['bad', []],\n\t\\ ['drinks', ['drink']],\n\t\\ ['drinkstable', ['drinktable', 'drinkable', 'drink table']],\n \\ ['drinkablestable', ['drinkabletable', 'drinkables table', 'drinkable table']],\n\t\\ ])\nendfunc",
"function FirstSpellWord()\n call feedkeys(\"/^start:\\n\", 'tx')\n normal ]smm\n let [str, a] = spellbadword()\n return str\nendfunc",
"function SecondSpellWord()\n normal `m]s\n let [str, a] = spellbadword()\n return str\nendfunc",
"\" Test with SAL instead of SOFO items; test automatic reloading\nfunc Test_spell_sal_and_addition()\n set spellfile=\n call writefile(g:test_data_dic1, \"Xtest.dic\")\n call writefile(g:test_data_aff_sal, \"Xtest.aff\")\n mkspell! Xtest Xtest\n set spl=Xtest.utf-8.spl spell\n call assert_equal('kbltykk', soundfold('goobledygoook'))\n call assert_equal('kprnfn', soundfold('kóopërÿnôven'))\n call assert_equal('*fls kswts tl', soundfold('oeverloos gezwets edale'))",
" \"also use an addition file\n call writefile([\"/regions=usgbnz\", \"elequint/2\", \"elekwint/3\"], \"Xtest.utf-8.add\")\n mkspell! Xtest.utf-8.add.spl Xtest.utf-8.add",
" bwipe!\n call setline(1, [\"start: elequint test elekwint test elekwent asdf\"])",
" set spellfile=Xtest.utf-8.add\n call assert_equal(\"elekwent\", FirstSpellWord())",
" set spl=Xtest_us.utf-8.spl\n call assert_equal(\"elequint\", FirstSpellWord())\n call assert_equal(\"elekwint\", SecondSpellWord())",
" set spl=Xtest_gb.utf-8.spl\n call assert_equal(\"elekwint\", FirstSpellWord())\n call assert_equal(\"elekwent\", SecondSpellWord())",
" set spl=Xtest_nz.utf-8.spl\n call assert_equal(\"elequint\", FirstSpellWord())\n call assert_equal(\"elekwent\", SecondSpellWord())",
" set spl=Xtest_ca.utf-8.spl\n call assert_equal(\"elequint\", FirstSpellWord())\n call assert_equal(\"elekwint\", SecondSpellWord())",
" set spellfile=\n set spl&\nendfunc",
"func Test_spellfile_value()\n set spellfile=Xdir/Xtest.utf-8.add\n set spellfile=Xdir/Xtest.utf-8.add,Xtest_other.add\n set spellfile=\nendfunc",
"func Test_no_crash_with_weird_text()\n new\n let lines =<< trim END\n r<sfile>\n ",
"\n \n END\n call setline(1, lines)\n exe \"%norm \\<C-v>ez=>\\<C-v>wzG\"",
" bwipe!\nendfunc",
"\" Invalid bytes may cause trouble when creating the word list.\nfunc Test_check_for_valid_word()\n call assert_fails(\"spellgood! 0\u0002\\xac\", 'E1280:')\nendfunc",
"\" This was going over the end of the word\nfunc Test_word_index()\n new\n norm R0\n spellgood! fl0\n sil norm z=",
" bwipe!\n \" clear the word list\n set enc=utf-8\n call delete('Xtmpfile')\nendfunc\n",
"",
"\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,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [1491, 804, 736], "buggy_code_start_loc": [1278, 804, 736], "filenames": ["src/spell.c", "src/testdir/test_spell_utf8.vim", "src/version.c"], "fixing_code_end_loc": [1495, 820, 739], "fixing_code_start_loc": [1278, 805, 737], "message": "Use After Free in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B6CDC65-37D1-4A6A-B6C5-7B58DC5757ED", "versionEndExcluding": "8.2.5072", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "0146DEE5-EF72-48C3-9DDD-28EA3595BDD1", "versionEndExcluding": "11.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7B7BC361-3A04-4C88-A3AE-82B9993A73A0", "versionEndExcluding": "12.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use After Free in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Un Uso de Memoria Previamente Liberada en el repositorio GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2042", "lastModified": "2023-05-03T12:15:40.820", "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": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 0.8, "impactScore": 6.0, "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-06-10T19:15:08.813", "references": [{"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/28"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/41"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/43"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/45"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/8628b4cd-4055-4059-aed4-64f7fdc10eba"}, {"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"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213443"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213444"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213488"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, "type": "CWE-416"}
| 317
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"\" Test for spell checking with 'encoding' set to utf-8",
"source check.vim\nCheckFeature spell",
"scriptencoding utf-8",
"func TearDown()\n set nospell\n call delete('Xtest.aff')\n call delete('Xtest.dic')\n call delete('Xtest.utf-8.add')\n call delete('Xtest.utf-8.add.spl')\n call delete('Xtest.utf-8.spl')\n call delete('Xtest.utf-8.sug')\nendfunc",
"let g:test_data_aff1 = [\n \\\"SET ISO8859-1\",\n \\\"TRY esianrtolcdugmphbyfvkwjkqxz-ëéèêïîäàâöüû'ESIANRTOLCDUGMPHBYFVKWJKQXZ\",\n \\\"\",\n \\\"FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ\",\n \\\"LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ\",\n \\\"UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ\",\n \\\"\",\n \\\"SOFOFROM abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xBF\",\n \\\"SOFOTO ebctefghejklnnepkrstevvkesebctefghejklnnepkrstevvkeseeeeeeeceeeeeeeedneeeeeeeeeeepseeeeeeeeceeeeeeeedneeeeeeeeeeep?\",\n \\\"\",\n \\\"MIDWORD\\t'-\",\n \\\"\",\n \\\"KEP =\",\n \\\"RAR ?\",\n \\\"BAD !\",\n \\\"\",\n \\\"PFX I N 1\",\n \\\"PFX I 0 in .\",\n \\\"\",\n \\\"PFX O Y 1\",\n \\\"PFX O 0 out .\",\n \\\"\",\n \\\"SFX S Y 2\",\n \\\"SFX S 0 s [^s]\",\n \\\"SFX S 0 es s\",\n \\\"\",\n \\\"SFX N N 3\",\n \\\"SFX N 0 en [^n]\",\n \\\"SFX N 0 nen n\",\n \\\"SFX N 0 n .\",\n \\\"\",\n \\\"REP 3\",\n \\\"REP g ch\",\n \\\"REP ch g\",\n \\\"REP svp s.v.p.\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\"\n \\ ]\nlet g:test_data_dic1 = [\n \\\"123456\",\n \\\"test/NO\",\n \\\"# comment\",\n \\\"wrong\",\n \\\"Comment\",\n \\\"OK\",\n \\\"uk\",\n \\\"put/ISO\",\n \\\"the end\",\n \\\"deol\",\n \\\"d\\xE9\\xF4r\",\n \\ ]\nlet g:test_data_aff2 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FOL \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"LOW \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"UPP \\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xFF\",\n \\\"\",\n \\\"PFXPOSTPONE\",\n \\\"\",\n \\\"MIDWORD\\t'-\",\n \\\"\",\n \\\"KEP =\",\n \\\"RAR ?\",\n \\\"BAD !\",\n \\\"\",\n \\\"PFX I N 1\",\n \\\"PFX I 0 in .\",\n \\\"\",\n \\\"PFX O Y 1\",\n \\\"PFX O 0 out [a-z]\",\n \\\"\",\n \\\"SFX S Y 2\",\n \\\"SFX S 0 s [^s]\",\n \\\"SFX S 0 es s\",\n \\\"\",\n \\\"SFX N N 3\",\n \\\"SFX N 0 en [^n]\",\n \\\"SFX N 0 nen n\",\n \\\"SFX N 0 n .\",\n \\\"\",\n \\\"REP 3\",\n \\\"REP g ch\",\n \\\"REP ch g\",\n \\\"REP svp s.v.p.\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\",\n \\ ]\nlet g:test_data_aff3 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"COMPOUNDMIN 3\",\n \\\"COMPOUNDRULE m*\",\n \\\"NEEDCOMPOUND x\",\n \\ ]\nlet g:test_data_dic3 = [\n \\\"1234\",\n \\\"foo/m\",\n \\\"bar/mx\",\n \\\"m\\xEF/m\",\n \\\"la/mx\",\n \\ ]\nlet g:test_data_aff4 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FOL \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"LOW \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"UPP \\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xFF\",\n \\\"\",\n \\\"COMPOUNDRULE m+\",\n \\\"COMPOUNDRULE sm*e\",\n \\\"COMPOUNDRULE sm+\",\n \\\"COMPOUNDMIN 3\",\n \\\"COMPOUNDWORDMAX 3\",\n \\\"COMPOUNDFORBIDFLAG t\",\n \\\"\",\n \\\"COMPOUNDSYLMAX 5\",\n \\\"SYLLABLE a\\xE1e\\xE9i\\xEDo\\xF3\\xF6\\xF5u\\xFA\\xFC\\xFBy/aa/au/ea/ee/ei/ie/oa/oe/oo/ou/uu/ui\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\",\n \\\"\",\n \\\"NEEDAFFIX x\",\n \\\"\",\n \\\"PFXPOSTPONE\",\n \\\"\",\n \\\"MIDWORD '-\",\n \\\"\",\n \\\"SFX q N 1\",\n \\\"SFX q 0 -ok .\",\n \\\"\",\n \\\"SFX a Y 2\",\n \\\"SFX a 0 s .\",\n \\\"SFX a 0 ize/t .\",\n \\\"\",\n \\\"PFX p N 1\",\n \\\"PFX p 0 pre .\",\n \\\"\",\n \\\"PFX P N 1\",\n \\\"PFX P 0 nou .\",\n \\ ]\nlet g:test_data_dic4 = [\n \\\"1234\",\n \\\"word/mP\",\n \\\"util/am\",\n \\\"pro/xq\",\n \\\"tomato/m\",\n \\\"bork/mp\",\n \\\"start/s\",\n \\\"end/e\",\n \\ ]\nlet g:test_data_aff5 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FLAG long\",\n \\\"\",\n \\\"NEEDAFFIX !!\",\n \\\"\",\n \\\"COMPOUNDRULE ssmm*ee\",\n \\\"\",\n \\\"NEEDCOMPOUND xx\",\n \\\"COMPOUNDPERMITFLAG pp\",\n \\\"\",\n \\\"SFX 13 Y 1\",\n \\\"SFX 13 0 bork .\",\n \\\"\",\n \\\"SFX a1 Y 1\",\n \\\"SFX a1 0 a1 .\",\n \\\"\",\n \\\"SFX a\\xE9 Y 1\",\n \\\"SFX a\\xE9 0 a\\xE9 .\",\n \\\"\",\n \\\"PFX zz Y 1\",\n \\\"PFX zz 0 pre/pp .\",\n \\\"\",\n \\\"PFX yy Y 1\",\n \\\"PFX yy 0 nou .\",\n \\ ]\nlet g:test_data_dic5 = [\n \\\"1234\",\n \\\"foo/a1a\\xE9!!\",\n \\\"bar/zz13ee\",\n \\\"start/ss\",\n \\\"end/eeyy\",\n \\\"middle/mmxx\",\n \\ ]\nlet g:test_data_aff6 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FLAG caplong\",\n \\\"\",\n \\\"NEEDAFFIX A!\",\n \\\"\",\n \\\"COMPOUNDRULE sMm*Ee\",\n \\\"\",\n \\\"NEEDCOMPOUND Xx\",\n \\\"\",\n \\\"COMPOUNDPERMITFLAG p\",\n \\\"\",\n \\\"SFX N3 Y 1\",\n \\\"SFX N3 0 bork .\",\n \\\"\",\n \\\"SFX A1 Y 1\",\n \\\"SFX A1 0 a1 .\",\n \\\"\",\n \\\"SFX A\\xE9 Y 1\",\n \\\"SFX A\\xE9 0 a\\xE9 .\",\n \\\"\",\n \\\"PFX Zz Y 1\",\n \\\"PFX Zz 0 pre/p .\",\n \\ ]\nlet g:test_data_dic6 = [\n \\\"1234\",\n \\\"mee/A1A\\xE9A!\",\n \\\"bar/ZzN3Ee\",\n \\\"lead/s\",\n \\\"end/Ee\",\n \\\"middle/MmXx\",\n \\ ]\nlet g:test_data_aff7 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"FLAG num\",\n \\\"\",\n \\\"NEEDAFFIX 9999\",\n \\\"\",\n \\\"COMPOUNDRULE 2,77*123\",\n \\\"\",\n \\\"NEEDCOMPOUND 1\",\n \\\"COMPOUNDPERMITFLAG 432\",\n \\\"\",\n \\\"SFX 61003 Y 1\",\n \\\"SFX 61003 0 meat .\",\n \\\"\",\n \\\"SFX 0 Y 1\",\n \\\"SFX 0 0 zero .\",\n \\\"\",\n \\\"SFX 391 Y 1\",\n \\\"SFX 391 0 a1 .\",\n \\\"\",\n \\\"SFX 111 Y 1\",\n \\\"SFX 111 0 a\\xE9 .\",\n \\\"\",\n \\\"PFX 17 Y 1\",\n \\\"PFX 17 0 pre/432 .\",\n \\ ]\nlet g:test_data_dic7 = [\n \\\"1234\",\n \\\"mee/0,391,111,9999\",\n \\\"bar/17,61003,123\",\n \\\"lead/2\",\n \\\"tail/123\",\n \\\"middle/77,1\",\n \\ ]\nlet g:test_data_aff8 = [\n \\\"SET ISO8859-1\",\n \\\"\",\n \\\"NOSPLITSUGS\",\n \\ ]\nlet g:test_data_dic8 = [\n \\\"1234\",\n \\\"foo\",\n \\\"bar\",\n \\\"faabar\",\n \\ ]\nlet g:test_data_aff9 = [\n \\ ]\nlet g:test_data_dic9 = [\n \\\"1234\",\n \\\"foo\",\n \\\"bar\",\n \\ ]\nlet g:test_data_aff10 = [\n \\\"COMPOUNDRULE se\",\n \\\"COMPOUNDPERMITFLAG p\",\n \\\"\",\n \\\"SFX A Y 1\",\n \\\"SFX A 0 able/Mp .\",\n \\\"\",\n \\\"SFX M Y 1\",\n \\\"SFX M 0 s .\",\n \\ ]\nlet g:test_data_dic10 = [\n \\\"1234\",\n \\\"drink/As\",\n \\\"table/e\",\n \\ ]\nlet g:test_data_aff_sal = [\n \\\"SET ISO8859-1\",\n \\\"TRY esianrtolcdugmphbyfvkwjkqxz-\\xEB\\xE9\\xE8\\xEA\\xEF\\xEE\\xE4\\xE0\\xE2\\xF6\\xFC\\xFB'ESIANRTOLCDUGMPHBYFVKWJKQXZ\",\n \\\"\",\n \\\"FOL \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"LOW \\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xDF\\xFF\",\n \\\"UPP \\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD8\\xD9\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xFF\",\n \\\"\",\n \\\"MIDWORD\\t'-\",\n \\\"\",\n \\\"KEP =\",\n \\\"RAR ?\",\n \\\"BAD !\",\n \\\"\",\n \\\"PFX I N 1\",\n \\\"PFX I 0 in .\",\n \\\"\",\n \\\"PFX O Y 1\",\n \\\"PFX O 0 out .\",\n \\\"\",\n \\\"SFX S Y 2\",\n \\\"SFX S 0 s [^s]\",\n \\\"SFX S 0 es s\",\n \\\"\",\n \\\"SFX N N 3\",\n \\\"SFX N 0 en [^n]\",\n \\\"SFX N 0 nen n\",\n \\\"SFX N 0 n .\",\n \\\"\",\n \\\"REP 3\",\n \\\"REP g ch\",\n \\\"REP ch g\",\n \\\"REP svp s.v.p.\",\n \\\"\",\n \\\"MAP 9\",\n \\\"MAP a\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\",\n \\\"MAP e\\xE8\\xE9\\xEA\\xEB\",\n \\\"MAP i\\xEC\\xED\\xEE\\xEF\",\n \\\"MAP o\\xF2\\xF3\\xF4\\xF5\\xF6\",\n \\\"MAP u\\xF9\\xFA\\xFB\\xFC\",\n \\\"MAP n\\xF1\",\n \\\"MAP c\\xE7\",\n \\\"MAP y\\xFF\\xFD\",\n \\\"MAP s\\xDF\",\n \\\"\",\n \\\"SAL AH(AEIOUY)-^ *H\",\n \\\"SAL AR(AEIOUY)-^ *R\",\n \\\"SAL A(HR)^ *\",\n \\\"SAL A^ *\",\n \\\"SAL AH(AEIOUY)- H\",\n \\\"SAL AR(AEIOUY)- R\",\n \\\"SAL A(HR) _\",\n \\\"SAL \\xC0^ *\",\n \\\"SAL \\xC5^ *\",\n \\\"SAL BB- _\",\n \\\"SAL B B\",\n \\\"SAL CQ- _\",\n \\\"SAL CIA X\",\n \\\"SAL CH X\",\n \\\"SAL C(EIY)- S\",\n \\\"SAL CK K\",\n \\\"SAL COUGH^ KF\",\n \\\"SAL CC< C\",\n \\\"SAL C K\",\n \\\"SAL DG(EIY) K\",\n \\\"SAL DD- _\",\n \\\"SAL D T\",\n \\\"SAL \\xC9< E\",\n \\\"SAL EH(AEIOUY)-^ *H\",\n \\\"SAL ER(AEIOUY)-^ *R\",\n \\\"SAL E(HR)^ *\",\n \\\"SAL ENOUGH^$ *NF\",\n \\\"SAL E^ *\",\n \\\"SAL EH(AEIOUY)- H\",\n \\\"SAL ER(AEIOUY)- R\",\n \\\"SAL E(HR) _\",\n \\\"SAL FF- _\",\n \\\"SAL F F\",\n \\\"SAL GN^ N\",\n \\\"SAL GN$ N\",\n \\\"SAL GNS$ NS\",\n \\\"SAL GNED$ N\",\n \\\"SAL GH(AEIOUY)- K\",\n \\\"SAL GH _\",\n \\\"SAL GG9 K\",\n \\\"SAL G K\",\n \\\"SAL H H\",\n \\\"SAL IH(AEIOUY)-^ *H\",\n \\\"SAL IR(AEIOUY)-^ *R\",\n \\\"SAL I(HR)^ *\",\n \\\"SAL I^ *\",\n \\\"SAL ING6 N\",\n \\\"SAL IH(AEIOUY)- H\",\n \\\"SAL IR(AEIOUY)- R\",\n \\\"SAL I(HR) _\",\n \\\"SAL J K\",\n \\\"SAL KN^ N\",\n \\\"SAL KK- _\",\n \\\"SAL K K\",\n \\\"SAL LAUGH^ LF\",\n \\\"SAL LL- _\",\n \\\"SAL L L\",\n \\\"SAL MB$ M\",\n \\\"SAL MM M\",\n \\\"SAL M M\",\n \\\"SAL NN- _\",\n \\\"SAL N N\",\n \\\"SAL OH(AEIOUY)-^ *H\",\n \\\"SAL OR(AEIOUY)-^ *R\",\n \\\"SAL O(HR)^ *\",\n \\\"SAL O^ *\",\n \\\"SAL OH(AEIOUY)- H\",\n \\\"SAL OR(AEIOUY)- R\",\n \\\"SAL O(HR) _\",\n \\\"SAL PH F\",\n \\\"SAL PN^ N\",\n \\\"SAL PP- _\",\n \\\"SAL P P\",\n \\\"SAL Q K\",\n \\\"SAL RH^ R\",\n \\\"SAL ROUGH^ RF\",\n \\\"SAL RR- _\",\n \\\"SAL R R\",\n \\\"SAL SCH(EOU)- SK\",\n \\\"SAL SC(IEY)- S\",\n \\\"SAL SH X\",\n \\\"SAL SI(AO)- X\",\n \\\"SAL SS- _\",\n \\\"SAL S S\",\n \\\"SAL TI(AO)- X\",\n \\\"SAL TH @\",\n \\\"SAL TCH-- _\",\n \\\"SAL TOUGH^ TF\",\n \\\"SAL TT- _\",\n \\\"SAL T T\",\n \\\"SAL UH(AEIOUY)-^ *H\",\n \\\"SAL UR(AEIOUY)-^ *R\",\n \\\"SAL U(HR)^ *\",\n \\\"SAL U^ *\",\n \\\"SAL UH(AEIOUY)- H\",\n \\\"SAL UR(AEIOUY)- R\",\n \\\"SAL U(HR) _\",\n \\\"SAL V^ W\",\n \\\"SAL V F\",\n \\\"SAL WR^ R\",\n \\\"SAL WH^ W\",\n \\\"SAL W(AEIOU)- W\",\n \\\"SAL X^ S\",\n \\\"SAL X KS\",\n \\\"SAL Y(AEIOU)- Y\",\n \\\"SAL ZZ- _\",\n \\\"SAL Z S\",\n \\ ]",
"func LoadAffAndDic(aff_contents, dic_contents)\n set enc=utf-8\n set spellfile=\n call writefile(a:aff_contents, \"Xtest.aff\")\n call writefile(a:dic_contents, \"Xtest.dic\")\n \" Generate a .spl file from a .dic and .aff file.\n mkspell! Xtest Xtest\n \" use that spell file\n set spl=Xtest.utf-8.spl spell\nendfunc",
"func ListWords()\n spelldump\n %yank\n quit\n return split(@\", \"\\n\")\nendfunc",
"func TestGoodBadBase()\n exe '1;/^good:'\n normal 0f:]s\n let prevbad = ''\n let result = []\n while 1\n let [bad, a] = spellbadword()\n if bad == '' || bad == prevbad || bad == 'badend'\n break\n endif\n let prevbad = bad\n let lst = bad->spellsuggest(3)\n normal mm",
" call add(result, [bad, lst])\n normal `m]s\n endwhile\n return result\nendfunc",
"func RunGoodBad(good, bad, expected_words, expected_bad_words)\n %bwipe!\n call setline(1, ['', \"good: \", a:good, a:bad, \" badend \"])\n let words = ListWords()\n call assert_equal(a:expected_words, words[1:-1])\n let bad_words = TestGoodBadBase()\n call assert_equal(a:expected_bad_words, bad_words)\n %bwipe!\nendfunc",
"func Test_spell_basic()\n call LoadAffAndDic(g:test_data_aff1, g:test_data_dic1)\n call RunGoodBad(\"wrong OK puts. Test the end\",\n \\ \"bad: inputs comment ok Ok. test d\\u00E9\\u00F4l end the\",\n \\[\"Comment\", \"deol\", \"d\\u00E9\\u00F4r\", \"input\", \"OK\", \"output\", \"outputs\", \"outtest\", \"put\", \"puts\",\n \\ \"test\", \"testen\", \"testn\", \"the end\", \"uk\", \"wrong\"],\n \\[\n \\ [\"bad\", [\"put\", \"uk\", \"OK\"]],\n \\ [\"inputs\", [\"input\", \"puts\", \"outputs\"]],\n \\ [\"comment\", [\"Comment\", \"outtest\", \"the end\"]],\n \\ [\"ok\", [\"OK\", \"uk\", \"put\"]],\n \\ [\"Ok\", [\"OK\", \"Uk\", \"Put\"]],\n \\ [\"test\", [\"Test\", \"testn\", \"testen\"]],\n \\ [\"d\\u00E9\\u00F4l\", [\"deol\", \"d\\u00E9\\u00F4r\", \"test\"]],\n \\ [\"end\", [\"put\", \"uk\", \"test\"]],\n \\ [\"the\", [\"put\", \"uk\", \"test\"]],\n \\ ]\n \\ )",
" call assert_equal(\"gebletegek\", soundfold('goobledygoook'))\n call assert_equal(\"kepereneven\", 'kóopërÿnôven'->soundfold())\n call assert_equal(\"everles gesvets etele\", soundfold('oeverloos gezwets edale'))\nendfunc",
"\" Postponed prefixes\nfunc Test_spell_prefixes()\n call LoadAffAndDic(g:test_data_aff2, g:test_data_dic1)\n call RunGoodBad(\"puts\",\n \\ \"bad: inputs comment ok Ok end the. test d\\u00E9\\u00F4l\",\n \\ [\"Comment\", \"deol\", \"d\\u00E9\\u00F4r\", \"OK\", \"put\", \"input\", \"output\", \"puts\", \"outputs\", \"test\", \"outtest\", \"testen\", \"testn\", \"the end\", \"uk\", \"wrong\"],\n \\ [\n \\ [\"bad\", [\"put\", \"uk\", \"OK\"]],\n \\ [\"inputs\", [\"input\", \"puts\", \"outputs\"]],\n \\ [\"comment\", [\"Comment\"]],\n \\ [\"ok\", [\"OK\", \"uk\", \"put\"]],\n \\ [\"Ok\", [\"OK\", \"Uk\", \"Put\"]],\n \\ [\"end\", [\"put\", \"uk\", \"deol\"]],\n \\ [\"the\", [\"put\", \"uk\", \"test\"]],\n \\ [\"test\", [\"Test\", \"testn\", \"testen\"]],\n \\ [\"d\\u00E9\\u00F4l\", [\"deol\", \"d\\u00E9\\u00F4r\", \"test\"]],\n \\ ])\nendfunc",
"\"Compound words\nfunc Test_spell_compound()\n call LoadAffAndDic(g:test_data_aff3, g:test_data_dic3)\n call RunGoodBad(\"foo m\\u00EF foobar foofoobar barfoo barbarfoo\",\n \\ \"bad: bar la foom\\u00EF barm\\u00EF m\\u00EFfoo m\\u00EFbar m\\u00EFm\\u00EF lala m\\u00EFla lam\\u00EF foola labar\",\n \\ [\"foo\", \"m\\u00EF\"],\n \\ [\n \\ [\"bad\", [\"foo\", \"m\\u00EF\"]],\n \\ [\"bar\", [\"barfoo\", \"foobar\", \"foo\"]],\n \\ [\"la\", [\"m\\u00EF\", \"foo\"]],\n \\ [\"foom\\u00EF\", [\"foo m\\u00EF\", \"foo\", \"foofoo\"]],\n \\ [\"barm\\u00EF\", [\"barfoo\", \"m\\u00EF\", \"barbar\"]],\n \\ [\"m\\u00EFfoo\", [\"m\\u00EF foo\", \"foo\", \"foofoo\"]],\n \\ [\"m\\u00EFbar\", [\"foobar\", \"barbar\", \"m\\u00EF\"]],\n \\ [\"m\\u00EFm\\u00EF\", [\"m\\u00EF m\\u00EF\", \"m\\u00EF\"]],\n \\ [\"lala\", []],\n \\ [\"m\\u00EFla\", [\"m\\u00EF\", \"m\\u00EF m\\u00EF\"]],\n \\ [\"lam\\u00EF\", [\"m\\u00EF\", \"m\\u00EF m\\u00EF\"]],\n \\ [\"foola\", [\"foo\", \"foobar\", \"foofoo\"]],\n \\ [\"labar\", [\"barbar\", \"foobar\"]],\n \\ ])",
" call LoadAffAndDic(g:test_data_aff4, g:test_data_dic4)\n call RunGoodBad(\"word util bork prebork start end wordutil wordutils pro-ok bork borkbork borkborkbork borkborkborkbork borkborkborkborkbork tomato tomatotomato startend startword startwordword startwordend startwordwordend startwordwordwordend prebork preborkbork preborkborkbork nouword\",\n \\ \"bad: wordutilize pro borkborkborkborkborkbork tomatotomatotomato endstart endend startstart wordend wordstart preborkprebork preborkpreborkbork startwordwordwordwordend borkpreborkpreborkbork utilsbork startnouword\",\n \\ [\"bork\", \"prebork\", \"end\", \"pro-ok\", \"start\", \"tomato\", \"util\", \"utilize\", \"utils\", \"word\", \"nouword\"],\n \\ [\n \\ [\"bad\", [\"end\", \"bork\", \"word\"]],\n \\ [\"wordutilize\", [\"word utilize\", \"wordutils\", \"wordutil\"]],\n \\ [\"pro\", [\"bork\", \"word\", \"end\"]],\n \\ [\"borkborkborkborkborkbork\", [\"bork borkborkborkborkbork\", \"borkbork borkborkborkbork\", \"borkborkbork borkborkbork\"]],\n \\ [\"tomatotomatotomato\", [\"tomato tomatotomato\", \"tomatotomato tomato\", \"tomato tomato tomato\"]],\n \\ [\"endstart\", [\"end start\", \"start\"]],\n \\ [\"endend\", [\"end end\", \"end\"]],\n \\ [\"startstart\", [\"start start\"]],\n \\ [\"wordend\", [\"word end\", \"word\", \"wordword\"]],\n \\ [\"wordstart\", [\"word start\", \"bork start\"]],\n \\ [\"preborkprebork\", [\"prebork prebork\", \"preborkbork\", \"preborkborkbork\"]],\n \\ [\"preborkpreborkbork\", [\"prebork preborkbork\", \"preborkborkbork\", \"preborkborkborkbork\"]],\n \\ [\"startwordwordwordwordend\", [\"startwordwordwordword end\", \"startwordwordwordword\", \"start wordwordwordword end\"]],\n \\ [\"borkpreborkpreborkbork\", [\"bork preborkpreborkbork\", \"bork prebork preborkbork\", \"bork preborkprebork bork\"]],\n \\ [\"utilsbork\", [\"utilbork\", \"utils bork\", \"util bork\"]],\n \\ [\"startnouword\", [\"start nouword\", \"startword\", \"startborkword\"]],\n \\ ])",
"endfunc",
"\" Test affix flags with two characters\nfunc Test_spell_affix()\n call LoadAffAndDic(g:test_data_aff5, g:test_data_dic5)\n call RunGoodBad(\"fooa1 fooa\\u00E9 bar prebar barbork prebarbork startprebar start end startend startmiddleend nouend\",\n \\ \"bad: foo fooa2 prabar probarbirk middle startmiddle middleend endstart startprobar startnouend\",\n \\ [\"bar\", \"barbork\", \"end\", \"fooa1\", \"fooa\\u00E9\", \"nouend\", \"prebar\", \"prebarbork\", \"start\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"end\", \"fooa1\"]],\n \\ [\"foo\", [\"fooa1\", \"bar\", \"end\"]],\n \\ [\"fooa2\", [\"fooa1\", \"fooa\\u00E9\", \"bar\"]],\n \\ [\"prabar\", [\"prebar\", \"bar\", \"bar bar\"]],\n \\ [\"probarbirk\", [\"prebarbork\"]],\n \\ [\"middle\", []],\n \\ [\"startmiddle\", [\"startmiddleend\", \"startmiddlebar\"]],\n \\ [\"middleend\", []],\n \\ [\"endstart\", [\"end start\", \"start\"]],\n \\ [\"startprobar\", [\"startprebar\", \"start prebar\", \"startbar\"]],\n \\ [\"startnouend\", [\"start nouend\", \"startend\"]],\n \\ ])",
" call LoadAffAndDic(g:test_data_aff6, g:test_data_dic6)\n call RunGoodBad(\"meea1 meea\\u00E9 bar prebar barbork prebarbork leadprebar lead end leadend leadmiddleend\",\n \\ \"bad: mee meea2 prabar probarbirk middle leadmiddle middleend endlead leadprobar\",\n \\ [\"bar\", \"barbork\", \"end\", \"lead\", \"meea1\", \"meea\\u00E9\", \"prebar\", \"prebarbork\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"end\", \"lead\"]],\n \\ [\"mee\", [\"meea1\", \"bar\", \"end\"]],\n \\ [\"meea2\", [\"meea1\", \"meea\\u00E9\", \"lead\"]],\n \\ [\"prabar\", [\"prebar\", \"bar\", \"leadbar\"]],\n \\ [\"probarbirk\", [\"prebarbork\"]],\n \\ [\"middle\", []],\n \\ [\"leadmiddle\", [\"leadmiddleend\", \"leadmiddlebar\"]],\n \\ [\"middleend\", []],\n \\ [\"endlead\", [\"end lead\", \"lead\", \"end end\"]],\n \\ [\"leadprobar\", [\"leadprebar\", \"lead prebar\", \"leadbar\"]],\n \\ ])",
" call LoadAffAndDic(g:test_data_aff7, g:test_data_dic7)\n call RunGoodBad(\"meea1 meezero meea\\u00E9 bar prebar barmeat prebarmeat leadprebar lead tail leadtail leadmiddletail\",\n \\ \"bad: mee meea2 prabar probarmaat middle leadmiddle middletail taillead leadprobar\",\n \\ [\"bar\", \"barmeat\", \"lead\", \"meea1\", \"meea\\u00E9\", \"meezero\", \"prebar\", \"prebarmeat\", \"tail\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"lead\", \"tail\"]],\n \\ [\"mee\", [\"meea1\", \"bar\", \"lead\"]],\n \\ [\"meea2\", [\"meea1\", \"meea\\u00E9\", \"lead\"]],\n \\ [\"prabar\", [\"prebar\", \"bar\", \"leadbar\"]],\n \\ [\"probarmaat\", [\"prebarmeat\"]],\n \\ [\"middle\", []],\n \\ [\"leadmiddle\", [\"leadmiddlebar\"]],\n \\ [\"middletail\", []],\n \\ [\"taillead\", [\"tail lead\", \"tail\"]],\n \\ [\"leadprobar\", [\"leadprebar\", \"lead prebar\", \"leadbar\"]],\n \\ ])\nendfunc",
"func Test_spell_NOSLITSUGS()\n call LoadAffAndDic(g:test_data_aff8, g:test_data_dic8)\n call RunGoodBad(\"foo bar faabar\", \"bad: foobar barfoo\",\n \\ [\"bar\", \"faabar\", \"foo\"],\n \\ [\n \\ [\"bad\", [\"bar\", \"foo\"]],\n \\ [\"foobar\", [\"faabar\", \"foo bar\", \"bar\"]],\n \\ [\"barfoo\", [\"bar foo\", \"bar\", \"foo\"]],\n \\ ])\nendfunc",
"\" Numbers\nfunc Test_spell_Numbers()\n call LoadAffAndDic(g:test_data_aff9, g:test_data_dic9)\n call RunGoodBad(\"0b1011 0777 1234 0x01ff\", \"\",\n \\ [\"bar\", \"foo\"],\n \\ [\n \\ ])\nendfunc",
"\" Affix flags\nfunc Test_spell_affix_flags()\n call LoadAffAndDic(g:test_data_aff10, g:test_data_dic10)\n call RunGoodBad(\"drink drinkable drinkables drinktable drinkabletable\",\n\t\\ \"bad: drinks drinkstable drinkablestable\",\n \\ [\"drink\", \"drinkable\", \"drinkables\", \"table\"],\n \\ [['bad', []],\n\t\\ ['drinks', ['drink']],\n\t\\ ['drinkstable', ['drinktable', 'drinkable', 'drink table']],\n \\ ['drinkablestable', ['drinkabletable', 'drinkables table', 'drinkable table']],\n\t\\ ])\nendfunc",
"function FirstSpellWord()\n call feedkeys(\"/^start:\\n\", 'tx')\n normal ]smm\n let [str, a] = spellbadword()\n return str\nendfunc",
"function SecondSpellWord()\n normal `m]s\n let [str, a] = spellbadword()\n return str\nendfunc",
"\" Test with SAL instead of SOFO items; test automatic reloading\nfunc Test_spell_sal_and_addition()\n set spellfile=\n call writefile(g:test_data_dic1, \"Xtest.dic\")\n call writefile(g:test_data_aff_sal, \"Xtest.aff\")\n mkspell! Xtest Xtest\n set spl=Xtest.utf-8.spl spell\n call assert_equal('kbltykk', soundfold('goobledygoook'))\n call assert_equal('kprnfn', soundfold('kóopërÿnôven'))\n call assert_equal('*fls kswts tl', soundfold('oeverloos gezwets edale'))",
" \"also use an addition file\n call writefile([\"/regions=usgbnz\", \"elequint/2\", \"elekwint/3\"], \"Xtest.utf-8.add\")\n mkspell! Xtest.utf-8.add.spl Xtest.utf-8.add",
" bwipe!\n call setline(1, [\"start: elequint test elekwint test elekwent asdf\"])",
" set spellfile=Xtest.utf-8.add\n call assert_equal(\"elekwent\", FirstSpellWord())",
" set spl=Xtest_us.utf-8.spl\n call assert_equal(\"elequint\", FirstSpellWord())\n call assert_equal(\"elekwint\", SecondSpellWord())",
" set spl=Xtest_gb.utf-8.spl\n call assert_equal(\"elekwint\", FirstSpellWord())\n call assert_equal(\"elekwent\", SecondSpellWord())",
" set spl=Xtest_nz.utf-8.spl\n call assert_equal(\"elequint\", FirstSpellWord())\n call assert_equal(\"elekwent\", SecondSpellWord())",
" set spl=Xtest_ca.utf-8.spl\n call assert_equal(\"elequint\", FirstSpellWord())\n call assert_equal(\"elekwint\", SecondSpellWord())",
" set spellfile=\n set spl&\nendfunc",
"func Test_spellfile_value()\n set spellfile=Xdir/Xtest.utf-8.add\n set spellfile=Xdir/Xtest.utf-8.add,Xtest_other.add\n set spellfile=\nendfunc",
"func Test_no_crash_with_weird_text()\n new\n let lines =<< trim END\n r<sfile>\n ",
"\n \n END\n call setline(1, lines)\n exe \"%norm \\<C-v>ez=>\\<C-v>wzG\"",
" bwipe!\nendfunc",
"\" Invalid bytes may cause trouble when creating the word list.\nfunc Test_check_for_valid_word()\n call assert_fails(\"spellgood! 0\u0002\\xac\", 'E1280:')\nendfunc",
"\" This was going over the end of the word\nfunc Test_word_index()\n new\n norm R0\n spellgood! fl0\n sil norm z=",
" bwipe!\n \" clear the word list\n set enc=utf-8\n call delete('Xtmpfile')\nendfunc\n",
"func Test_check_empty_line()\n \" This was using freed memory\n enew\n spellgood! fl\n norm z=\n norm yy\n sil! norm P]svc\n norm P]s",
" \" set 'encoding' to clear the wordt list\n set enc=latin1\n set enc=utf-8\n bwipe!\nendfunc\n",
"\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [1491, 804, 736], "buggy_code_start_loc": [1278, 804, 736], "filenames": ["src/spell.c", "src/testdir/test_spell_utf8.vim", "src/version.c"], "fixing_code_end_loc": [1495, 820, 739], "fixing_code_start_loc": [1278, 805, 737], "message": "Use After Free in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B6CDC65-37D1-4A6A-B6C5-7B58DC5757ED", "versionEndExcluding": "8.2.5072", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "0146DEE5-EF72-48C3-9DDD-28EA3595BDD1", "versionEndExcluding": "11.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7B7BC361-3A04-4C88-A3AE-82B9993A73A0", "versionEndExcluding": "12.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use After Free in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Un Uso de Memoria Previamente Liberada en el repositorio GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2042", "lastModified": "2023-05-03T12:15:40.820", "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": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 0.8, "impactScore": 6.0, "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-06-10T19:15:08.813", "references": [{"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/28"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/41"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/43"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/45"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/8628b4cd-4055-4059-aed4-64f7fdc10eba"}, {"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"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213443"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213444"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213488"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, "type": "CWE-416"}
| 317
|
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 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 5071,\n/**/\n 5070,\n/**/\n 5069,\n/**/\n 5068,\n/**/\n 5067,\n/**/\n 5066,\n/**/\n 5065,\n/**/\n 5064,\n/**/\n 5063,\n/**/\n 5062,\n/**/\n 5061,\n/**/\n 5060,\n/**/\n 5059,\n/**/\n 5058,\n/**/\n 5057,\n/**/\n 5056,\n/**/\n 5055,\n/**/\n 5054,\n/**/\n 5053,\n/**/\n 5052,\n/**/\n 5051,\n/**/\n 5050,\n/**/\n 5049,\n/**/\n 5048,\n/**/\n 5047,\n/**/\n 5046,\n/**/\n 5045,\n/**/\n 5044,\n/**/\n 5043,\n/**/\n 5042,\n/**/\n 5041,\n/**/\n 5040,\n/**/\n 5039,\n/**/\n 5038,\n/**/\n 5037,\n/**/\n 5036,\n/**/\n 5035,\n/**/\n 5034,\n/**/\n 5033,\n/**/\n 5032,\n/**/\n 5031,\n/**/\n 5030,\n/**/\n 5029,\n/**/\n 5028,\n/**/\n 5027,\n/**/\n 5026,\n/**/\n 5025,\n/**/\n 5024,\n/**/\n 5023,\n/**/\n 5022,\n/**/\n 5021,\n/**/\n 5020,\n/**/\n 5019,\n/**/\n 5018,\n/**/\n 5017,\n/**/\n 5016,\n/**/\n 5015,\n/**/\n 5014,\n/**/\n 5013,\n/**/\n 5012,\n/**/\n 5011,\n/**/\n 5010,\n/**/\n 5009,\n/**/\n 5008,\n/**/\n 5007,\n/**/\n 5006,\n/**/\n 5005,\n/**/\n 5004,\n/**/\n 5003,\n/**/\n 5002,\n/**/\n 5001,\n/**/\n 5000,\n/**/\n 4999,\n/**/\n 4998,\n/**/\n 4997,\n/**/\n 4996,\n/**/\n 4995,\n/**/\n 4994,\n/**/\n 4993,\n/**/\n 4992,\n/**/\n 4991,\n/**/\n 4990,\n/**/\n 4989,\n/**/\n 4988,\n/**/\n 4987,\n/**/\n 4986,\n/**/\n 4985,\n/**/\n 4984,\n/**/\n 4983,\n/**/\n 4982,\n/**/\n 4981,\n/**/\n 4980,\n/**/\n 4979,\n/**/\n 4978,\n/**/\n 4977,\n/**/\n 4976,\n/**/\n 4975,\n/**/\n 4974,\n/**/\n 4973,\n/**/\n 4972,\n/**/\n 4971,\n/**/\n 4970,\n/**/\n 4969,\n/**/\n 4968,\n/**/\n 4967,\n/**/\n 4966,\n/**/\n 4965,\n/**/\n 4964,\n/**/\n 4963,\n/**/\n 4962,\n/**/\n 4961,\n/**/\n 4960,\n/**/\n 4959,\n/**/\n 4958,\n/**/\n 4957,\n/**/\n 4956,\n/**/\n 4955,\n/**/\n 4954,\n/**/\n 4953,\n/**/\n 4952,\n/**/\n 4951,\n/**/\n 4950,\n/**/\n 4949,\n/**/\n 4948,\n/**/\n 4947,\n/**/\n 4946,\n/**/\n 4945,\n/**/\n 4944,\n/**/\n 4943,\n/**/\n 4942,\n/**/\n 4941,\n/**/\n 4940,\n/**/\n 4939,\n/**/\n 4938,\n/**/\n 4937,\n/**/\n 4936,\n/**/\n 4935,\n/**/\n 4934,\n/**/\n 4933,\n/**/\n 4932,\n/**/\n 4931,\n/**/\n 4930,\n/**/\n 4929,\n/**/\n 4928,\n/**/\n 4927,\n/**/\n 4926,\n/**/\n 4925,\n/**/\n 4924,\n/**/\n 4923,\n/**/\n 4922,\n/**/\n 4921,\n/**/\n 4920,\n/**/\n 4919,\n/**/\n 4918,\n/**/\n 4917,\n/**/\n 4916,\n/**/\n 4915,\n/**/\n 4914,\n/**/\n 4913,\n/**/\n 4912,\n/**/\n 4911,\n/**/\n 4910,\n/**/\n 4909,\n/**/\n 4908,\n/**/\n 4907,\n/**/\n 4906,\n/**/\n 4905,\n/**/\n 4904,\n/**/\n 4903,\n/**/\n 4902,\n/**/\n 4901,\n/**/\n 4900,\n/**/\n 4899,\n/**/\n 4898,\n/**/\n 4897,\n/**/\n 4896,\n/**/\n 4895,\n/**/\n 4894,\n/**/\n 4893,\n/**/\n 4892,\n/**/\n 4891,\n/**/\n 4890,\n/**/\n 4889,\n/**/\n 4888,\n/**/\n 4887,\n/**/\n 4886,\n/**/\n 4885,\n/**/\n 4884,\n/**/\n 4883,\n/**/\n 4882,\n/**/\n 4881,\n/**/\n 4880,\n/**/\n 4879,\n/**/\n 4878,\n/**/\n 4877,\n/**/\n 4876,\n/**/\n 4875,\n/**/\n 4874,\n/**/\n 4873,\n/**/\n 4872,\n/**/\n 4871,\n/**/\n 4870,\n/**/\n 4869,\n/**/\n 4868,\n/**/\n 4867,\n/**/\n 4866,\n/**/\n 4865,\n/**/\n 4864,\n/**/\n 4863,\n/**/\n 4862,\n/**/\n 4861,\n/**/\n 4860,\n/**/\n 4859,\n/**/\n 4858,\n/**/\n 4857,\n/**/\n 4856,\n/**/\n 4855,\n/**/\n 4854,\n/**/\n 4853,\n/**/\n 4852,\n/**/\n 4851,\n/**/\n 4850,\n/**/\n 4849,\n/**/\n 4848,\n/**/\n 4847,\n/**/\n 4846,\n/**/\n 4845,\n/**/\n 4844,\n/**/\n 4843,\n/**/\n 4842,\n/**/\n 4841,\n/**/\n 4840,\n/**/\n 4839,\n/**/\n 4838,\n/**/\n 4837,\n/**/\n 4836,\n/**/\n 4835,\n/**/\n 4834,\n/**/\n 4833,\n/**/\n 4832,\n/**/\n 4831,\n/**/\n 4830,\n/**/\n 4829,\n/**/\n 4828,\n/**/\n 4827,\n/**/\n 4826,\n/**/\n 4825,\n/**/\n 4824,\n/**/\n 4823,\n/**/\n 4822,\n/**/\n 4821,\n/**/\n 4820,\n/**/\n 4819,\n/**/\n 4818,\n/**/\n 4817,\n/**/\n 4816,\n/**/\n 4815,\n/**/\n 4814,\n/**/\n 4813,\n/**/\n 4812,\n/**/\n 4811,\n/**/\n 4810,\n/**/\n 4809,\n/**/\n 4808,\n/**/\n 4807,\n/**/\n 4806,\n/**/\n 4805,\n/**/\n 4804,\n/**/\n 4803,\n/**/\n 4802,\n/**/\n 4801,\n/**/\n 4800,\n/**/\n 4799,\n/**/\n 4798,\n/**/\n 4797,\n/**/\n 4796,\n/**/\n 4795,\n/**/\n 4794,\n/**/\n 4793,\n/**/\n 4792,\n/**/\n 4791,\n/**/\n 4790,\n/**/\n 4789,\n/**/\n 4788,\n/**/\n 4787,\n/**/\n 4786,\n/**/\n 4785,\n/**/\n 4784,\n/**/\n 4783,\n/**/\n 4782,\n/**/\n 4781,\n/**/\n 4780,\n/**/\n 4779,\n/**/\n 4778,\n/**/\n 4777,\n/**/\n 4776,\n/**/\n 4775,\n/**/\n 4774,\n/**/\n 4773,\n/**/\n 4772,\n/**/\n 4771,\n/**/\n 4770,\n/**/\n 4769,\n/**/\n 4768,\n/**/\n 4767,\n/**/\n 4766,\n/**/\n 4765,\n/**/\n 4764,\n/**/\n 4763,\n/**/\n 4762,\n/**/\n 4761,\n/**/\n 4760,\n/**/\n 4759,\n/**/\n 4758,\n/**/\n 4757,\n/**/\n 4756,\n/**/\n 4755,\n/**/\n 4754,\n/**/\n 4753,\n/**/\n 4752,\n/**/\n 4751,\n/**/\n 4750,\n/**/\n 4749,\n/**/\n 4748,\n/**/\n 4747,\n/**/\n 4746,\n/**/\n 4745,\n/**/\n 4744,\n/**/\n 4743,\n/**/\n 4742,\n/**/\n 4741,\n/**/\n 4740,\n/**/\n 4739,\n/**/\n 4738,\n/**/\n 4737,\n/**/\n 4736,\n/**/\n 4735,\n/**/\n 4734,\n/**/\n 4733,\n/**/\n 4732,\n/**/\n 4731,\n/**/\n 4730,\n/**/\n 4729,\n/**/\n 4728,\n/**/\n 4727,\n/**/\n 4726,\n/**/\n 4725,\n/**/\n 4724,\n/**/\n 4723,\n/**/\n 4722,\n/**/\n 4721,\n/**/\n 4720,\n/**/\n 4719,\n/**/\n 4718,\n/**/\n 4717,\n/**/\n 4716,\n/**/\n 4715,\n/**/\n 4714,\n/**/\n 4713,\n/**/\n 4712,\n/**/\n 4711,\n/**/\n 4710,\n/**/\n 4709,\n/**/\n 4708,\n/**/\n 4707,\n/**/\n 4706,\n/**/\n 4705,\n/**/\n 4704,\n/**/\n 4703,\n/**/\n 4702,\n/**/\n 4701,\n/**/\n 4700,\n/**/\n 4699,\n/**/\n 4698,\n/**/\n 4697,\n/**/\n 4696,\n/**/\n 4695,\n/**/\n 4694,\n/**/\n 4693,\n/**/\n 4692,\n/**/\n 4691,\n/**/\n 4690,\n/**/\n 4689,\n/**/\n 4688,\n/**/\n 4687,\n/**/\n 4686,\n/**/\n 4685,\n/**/\n 4684,\n/**/\n 4683,\n/**/\n 4682,\n/**/\n 4681,\n/**/\n 4680,\n/**/\n 4679,\n/**/\n 4678,\n/**/\n 4677,\n/**/\n 4676,\n/**/\n 4675,\n/**/\n 4674,\n/**/\n 4673,\n/**/\n 4672,\n/**/\n 4671,\n/**/\n 4670,\n/**/\n 4669,\n/**/\n 4668,\n/**/\n 4667,\n/**/\n 4666,\n/**/\n 4665,\n/**/\n 4664,\n/**/\n 4663,\n/**/\n 4662,\n/**/\n 4661,\n/**/\n 4660,\n/**/\n 4659,\n/**/\n 4658,\n/**/\n 4657,\n/**/\n 4656,\n/**/\n 4655,\n/**/\n 4654,\n/**/\n 4653,\n/**/\n 4652,\n/**/\n 4651,\n/**/\n 4650,\n/**/\n 4649,\n/**/\n 4648,\n/**/\n 4647,\n/**/\n 4646,\n/**/\n 4645,\n/**/\n 4644,\n/**/\n 4643,\n/**/\n 4642,\n/**/\n 4641,\n/**/\n 4640,\n/**/\n 4639,\n/**/\n 4638,\n/**/\n 4637,\n/**/\n 4636,\n/**/\n 4635,\n/**/\n 4634,\n/**/\n 4633,\n/**/\n 4632,\n/**/\n 4631,\n/**/\n 4630,\n/**/\n 4629,\n/**/\n 4628,\n/**/\n 4627,\n/**/\n 4626,\n/**/\n 4625,\n/**/\n 4624,\n/**/\n 4623,\n/**/\n 4622,\n/**/\n 4621,\n/**/\n 4620,\n/**/\n 4619,\n/**/\n 4618,\n/**/\n 4617,\n/**/\n 4616,\n/**/\n 4615,\n/**/\n 4614,\n/**/\n 4613,\n/**/\n 4612,\n/**/\n 4611,\n/**/\n 4610,\n/**/\n 4609,\n/**/\n 4608,\n/**/\n 4607,\n/**/\n 4606,\n/**/\n 4605,\n/**/\n 4604,\n/**/\n 4603,\n/**/\n 4602,\n/**/\n 4601,\n/**/\n 4600,\n/**/\n 4599,\n/**/\n 4598,\n/**/\n 4597,\n/**/\n 4596,\n/**/\n 4595,\n/**/\n 4594,\n/**/\n 4593,\n/**/\n 4592,\n/**/\n 4591,\n/**/\n 4590,\n/**/\n 4589,\n/**/\n 4588,\n/**/\n 4587,\n/**/\n 4586,\n/**/\n 4585,\n/**/\n 4584,\n/**/\n 4583,\n/**/\n 4582,\n/**/\n 4581,\n/**/\n 4580,\n/**/\n 4579,\n/**/\n 4578,\n/**/\n 4577,\n/**/\n 4576,\n/**/\n 4575,\n/**/\n 4574,\n/**/\n 4573,\n/**/\n 4572,\n/**/\n 4571,\n/**/\n 4570,\n/**/\n 4569,\n/**/\n 4568,\n/**/\n 4567,\n/**/\n 4566,\n/**/\n 4565,\n/**/\n 4564,\n/**/\n 4563,\n/**/\n 4562,\n/**/\n 4561,\n/**/\n 4560,\n/**/\n 4559,\n/**/\n 4558,\n/**/\n 4557,\n/**/\n 4556,\n/**/\n 4555,\n/**/\n 4554,\n/**/\n 4553,\n/**/\n 4552,\n/**/\n 4551,\n/**/\n 4550,\n/**/\n 4549,\n/**/\n 4548,\n/**/\n 4547,\n/**/\n 4546,\n/**/\n 4545,\n/**/\n 4544,\n/**/\n 4543,\n/**/\n 4542,\n/**/\n 4541,\n/**/\n 4540,\n/**/\n 4539,\n/**/\n 4538,\n/**/\n 4537,\n/**/\n 4536,\n/**/\n 4535,\n/**/\n 4534,\n/**/\n 4533,\n/**/\n 4532,\n/**/\n 4531,\n/**/\n 4530,\n/**/\n 4529,\n/**/\n 4528,\n/**/\n 4527,\n/**/\n 4526,\n/**/\n 4525,\n/**/\n 4524,\n/**/\n 4523,\n/**/\n 4522,\n/**/\n 4521,\n/**/\n 4520,\n/**/\n 4519,\n/**/\n 4518,\n/**/\n 4517,\n/**/\n 4516,\n/**/\n 4515,\n/**/\n 4514,\n/**/\n 4513,\n/**/\n 4512,\n/**/\n 4511,\n/**/\n 4510,\n/**/\n 4509,\n/**/\n 4508,\n/**/\n 4507,\n/**/\n 4506,\n/**/\n 4505,\n/**/\n 4504,\n/**/\n 4503,\n/**/\n 4502,\n/**/\n 4501,\n/**/\n 4500,\n/**/\n 4499,\n/**/\n 4498,\n/**/\n 4497,\n/**/\n 4496,\n/**/\n 4495,\n/**/\n 4494,\n/**/\n 4493,\n/**/\n 4492,\n/**/\n 4491,\n/**/\n 4490,\n/**/\n 4489,\n/**/\n 4488,\n/**/\n 4487,\n/**/\n 4486,\n/**/\n 4485,\n/**/\n 4484,\n/**/\n 4483,\n/**/\n 4482,\n/**/\n 4481,\n/**/\n 4480,\n/**/\n 4479,\n/**/\n 4478,\n/**/\n 4477,\n/**/\n 4476,\n/**/\n 4475,\n/**/\n 4474,\n/**/\n 4473,\n/**/\n 4472,\n/**/\n 4471,\n/**/\n 4470,\n/**/\n 4469,\n/**/\n 4468,\n/**/\n 4467,\n/**/\n 4466,\n/**/\n 4465,\n/**/\n 4464,\n/**/\n 4463,\n/**/\n 4462,\n/**/\n 4461,\n/**/\n 4460,\n/**/\n 4459,\n/**/\n 4458,\n/**/\n 4457,\n/**/\n 4456,\n/**/\n 4455,\n/**/\n 4454,\n/**/\n 4453,\n/**/\n 4452,\n/**/\n 4451,\n/**/\n 4450,\n/**/\n 4449,\n/**/\n 4448,\n/**/\n 4447,\n/**/\n 4446,\n/**/\n 4445,\n/**/\n 4444,\n/**/\n 4443,\n/**/\n 4442,\n/**/\n 4441,\n/**/\n 4440,\n/**/\n 4439,\n/**/\n 4438,\n/**/\n 4437,\n/**/\n 4436,\n/**/\n 4435,\n/**/\n 4434,\n/**/\n 4433,\n/**/\n 4432,\n/**/\n 4431,\n/**/\n 4430,\n/**/\n 4429,\n/**/\n 4428,\n/**/\n 4427,\n/**/\n 4426,\n/**/\n 4425,\n/**/\n 4424,\n/**/\n 4423,\n/**/\n 4422,\n/**/\n 4421,\n/**/\n 4420,\n/**/\n 4419,\n/**/\n 4418,\n/**/\n 4417,\n/**/\n 4416,\n/**/\n 4415,\n/**/\n 4414,\n/**/\n 4413,\n/**/\n 4412,\n/**/\n 4411,\n/**/\n 4410,\n/**/\n 4409,\n/**/\n 4408,\n/**/\n 4407,\n/**/\n 4406,\n/**/\n 4405,\n/**/\n 4404,\n/**/\n 4403,\n/**/\n 4402,\n/**/\n 4401,\n/**/\n 4400,\n/**/\n 4399,\n/**/\n 4398,\n/**/\n 4397,\n/**/\n 4396,\n/**/\n 4395,\n/**/\n 4394,\n/**/\n 4393,\n/**/\n 4392,\n/**/\n 4391,\n/**/\n 4390,\n/**/\n 4389,\n/**/\n 4388,\n/**/\n 4387,\n/**/\n 4386,\n/**/\n 4385,\n/**/\n 4384,\n/**/\n 4383,\n/**/\n 4382,\n/**/\n 4381,\n/**/\n 4380,\n/**/\n 4379,\n/**/\n 4378,\n/**/\n 4377,\n/**/\n 4376,\n/**/\n 4375,\n/**/\n 4374,\n/**/\n 4373,\n/**/\n 4372,\n/**/\n 4371,\n/**/\n 4370,\n/**/\n 4369,\n/**/\n 4368,\n/**/\n 4367,\n/**/\n 4366,\n/**/\n 4365,\n/**/\n 4364,\n/**/\n 4363,\n/**/\n 4362,\n/**/\n 4361,\n/**/\n 4360,\n/**/\n 4359,\n/**/\n 4358,\n/**/\n 4357,\n/**/\n 4356,\n/**/\n 4355,\n/**/\n 4354,\n/**/\n 4353,\n/**/\n 4352,\n/**/\n 4351,\n/**/\n 4350,\n/**/\n 4349,\n/**/\n 4348,\n/**/\n 4347,\n/**/\n 4346,\n/**/\n 4345,\n/**/\n 4344,\n/**/\n 4343,\n/**/\n 4342,\n/**/\n 4341,\n/**/\n 4340,\n/**/\n 4339,\n/**/\n 4338,\n/**/\n 4337,\n/**/\n 4336,\n/**/\n 4335,\n/**/\n 4334,\n/**/\n 4333,\n/**/\n 4332,\n/**/\n 4331,\n/**/\n 4330,\n/**/\n 4329,\n/**/\n 4328,\n/**/\n 4327,\n/**/\n 4326,\n/**/\n 4325,\n/**/\n 4324,\n/**/\n 4323,\n/**/\n 4322,\n/**/\n 4321,\n/**/\n 4320,\n/**/\n 4319,\n/**/\n 4318,\n/**/\n 4317,\n/**/\n 4316,\n/**/\n 4315,\n/**/\n 4314,\n/**/\n 4313,\n/**/\n 4312,\n/**/\n 4311,\n/**/\n 4310,\n/**/\n 4309,\n/**/\n 4308,\n/**/\n 4307,\n/**/\n 4306,\n/**/\n 4305,\n/**/\n 4304,\n/**/\n 4303,\n/**/\n 4302,\n/**/\n 4301,\n/**/\n 4300,\n/**/\n 4299,\n/**/\n 4298,\n/**/\n 4297,\n/**/\n 4296,\n/**/\n 4295,\n/**/\n 4294,\n/**/\n 4293,\n/**/\n 4292,\n/**/\n 4291,\n/**/\n 4290,\n/**/\n 4289,\n/**/\n 4288,\n/**/\n 4287,\n/**/\n 4286,\n/**/\n 4285,\n/**/\n 4284,\n/**/\n 4283,\n/**/\n 4282,\n/**/\n 4281,\n/**/\n 4280,\n/**/\n 4279,\n/**/\n 4278,\n/**/\n 4277,\n/**/\n 4276,\n/**/\n 4275,\n/**/\n 4274,\n/**/\n 4273,\n/**/\n 4272,\n/**/\n 4271,\n/**/\n 4270,\n/**/\n 4269,\n/**/\n 4268,\n/**/\n 4267,\n/**/\n 4266,\n/**/\n 4265,\n/**/\n 4264,\n/**/\n 4263,\n/**/\n 4262,\n/**/\n 4261,\n/**/\n 4260,\n/**/\n 4259,\n/**/\n 4258,\n/**/\n 4257,\n/**/\n 4256,\n/**/\n 4255,\n/**/\n 4254,\n/**/\n 4253,\n/**/\n 4252,\n/**/\n 4251,\n/**/\n 4250,\n/**/\n 4249,\n/**/\n 4248,\n/**/\n 4247,\n/**/\n 4246,\n/**/\n 4245,\n/**/\n 4244,\n/**/\n 4243,\n/**/\n 4242,\n/**/\n 4241,\n/**/\n 4240,\n/**/\n 4239,\n/**/\n 4238,\n/**/\n 4237,\n/**/\n 4236,\n/**/\n 4235,\n/**/\n 4234,\n/**/\n 4233,\n/**/\n 4232,\n/**/\n 4231,\n/**/\n 4230,\n/**/\n 4229,\n/**/\n 4228,\n/**/\n 4227,\n/**/\n 4226,\n/**/\n 4225,\n/**/\n 4224,\n/**/\n 4223,\n/**/\n 4222,\n/**/\n 4221,\n/**/\n 4220,\n/**/\n 4219,\n/**/\n 4218,\n/**/\n 4217,\n/**/\n 4216,\n/**/\n 4215,\n/**/\n 4214,\n/**/\n 4213,\n/**/\n 4212,\n/**/\n 4211,\n/**/\n 4210,\n/**/\n 4209,\n/**/\n 4208,\n/**/\n 4207,\n/**/\n 4206,\n/**/\n 4205,\n/**/\n 4204,\n/**/\n 4203,\n/**/\n 4202,\n/**/\n 4201,\n/**/\n 4200,\n/**/\n 4199,\n/**/\n 4198,\n/**/\n 4197,\n/**/\n 4196,\n/**/\n 4195,\n/**/\n 4194,\n/**/\n 4193,\n/**/\n 4192,\n/**/\n 4191,\n/**/\n 4190,\n/**/\n 4189,\n/**/\n 4188,\n/**/\n 4187,\n/**/\n 4186,\n/**/\n 4185,\n/**/\n 4184,\n/**/\n 4183,\n/**/\n 4182,\n/**/\n 4181,\n/**/\n 4180,\n/**/\n 4179,\n/**/\n 4178,\n/**/\n 4177,\n/**/\n 4176,\n/**/\n 4175,\n/**/\n 4174,\n/**/\n 4173,\n/**/\n 4172,\n/**/\n 4171,\n/**/\n 4170,\n/**/\n 4169,\n/**/\n 4168,\n/**/\n 4167,\n/**/\n 4166,\n/**/\n 4165,\n/**/\n 4164,\n/**/\n 4163,\n/**/\n 4162,\n/**/\n 4161,\n/**/\n 4160,\n/**/\n 4159,\n/**/\n 4158,\n/**/\n 4157,\n/**/\n 4156,\n/**/\n 4155,\n/**/\n 4154,\n/**/\n 4153,\n/**/\n 4152,\n/**/\n 4151,\n/**/\n 4150,\n/**/\n 4149,\n/**/\n 4148,\n/**/\n 4147,\n/**/\n 4146,\n/**/\n 4145,\n/**/\n 4144,\n/**/\n 4143,\n/**/\n 4142,\n/**/\n 4141,\n/**/\n 4140,\n/**/\n 4139,\n/**/\n 4138,\n/**/\n 4137,\n/**/\n 4136,\n/**/\n 4135,\n/**/\n 4134,\n/**/\n 4133,\n/**/\n 4132,\n/**/\n 4131,\n/**/\n 4130,\n/**/\n 4129,\n/**/\n 4128,\n/**/\n 4127,\n/**/\n 4126,\n/**/\n 4125,\n/**/\n 4124,\n/**/\n 4123,\n/**/\n 4122,\n/**/\n 4121,\n/**/\n 4120,\n/**/\n 4119,\n/**/\n 4118,\n/**/\n 4117,\n/**/\n 4116,\n/**/\n 4115,\n/**/\n 4114,\n/**/\n 4113,\n/**/\n 4112,\n/**/\n 4111,\n/**/\n 4110,\n/**/\n 4109,\n/**/\n 4108,\n/**/\n 4107,\n/**/\n 4106,\n/**/\n 4105,\n/**/\n 4104,\n/**/\n 4103,\n/**/\n 4102,\n/**/\n 4101,\n/**/\n 4100,\n/**/\n 4099,\n/**/\n 4098,\n/**/\n 4097,\n/**/\n 4096,\n/**/\n 4095,\n/**/\n 4094,\n/**/\n 4093,\n/**/\n 4092,\n/**/\n 4091,\n/**/\n 4090,\n/**/\n 4089,\n/**/\n 4088,\n/**/\n 4087,\n/**/\n 4086,\n/**/\n 4085,\n/**/\n 4084,\n/**/\n 4083,\n/**/\n 4082,\n/**/\n 4081,\n/**/\n 4080,\n/**/\n 4079,\n/**/\n 4078,\n/**/\n 4077,\n/**/\n 4076,\n/**/\n 4075,\n/**/\n 4074,\n/**/\n 4073,\n/**/\n 4072,\n/**/\n 4071,\n/**/\n 4070,\n/**/\n 4069,\n/**/\n 4068,\n/**/\n 4067,\n/**/\n 4066,\n/**/\n 4065,\n/**/\n 4064,\n/**/\n 4063,\n/**/\n 4062,\n/**/\n 4061,\n/**/\n 4060,\n/**/\n 4059,\n/**/\n 4058,\n/**/\n 4057,\n/**/\n 4056,\n/**/\n 4055,\n/**/\n 4054,\n/**/\n 4053,\n/**/\n 4052,\n/**/\n 4051,\n/**/\n 4050,\n/**/\n 4049,\n/**/\n 4048,\n/**/\n 4047,\n/**/\n 4046,\n/**/\n 4045,\n/**/\n 4044,\n/**/\n 4043,\n/**/\n 4042,\n/**/\n 4041,\n/**/\n 4040,\n/**/\n 4039,\n/**/\n 4038,\n/**/\n 4037,\n/**/\n 4036,\n/**/\n 4035,\n/**/\n 4034,\n/**/\n 4033,\n/**/\n 4032,\n/**/\n 4031,\n/**/\n 4030,\n/**/\n 4029,\n/**/\n 4028,\n/**/\n 4027,\n/**/\n 4026,\n/**/\n 4025,\n/**/\n 4024,\n/**/\n 4023,\n/**/\n 4022,\n/**/\n 4021,\n/**/\n 4020,\n/**/\n 4019,\n/**/\n 4018,\n/**/\n 4017,\n/**/\n 4016,\n/**/\n 4015,\n/**/\n 4014,\n/**/\n 4013,\n/**/\n 4012,\n/**/\n 4011,\n/**/\n 4010,\n/**/\n 4009,\n/**/\n 4008,\n/**/\n 4007,\n/**/\n 4006,\n/**/\n 4005,\n/**/\n 4004,\n/**/\n 4003,\n/**/\n 4002,\n/**/\n 4001,\n/**/\n 4000,\n/**/\n 3999,\n/**/\n 3998,\n/**/\n 3997,\n/**/\n 3996,\n/**/\n 3995,\n/**/\n 3994,\n/**/\n 3993,\n/**/\n 3992,\n/**/\n 3991,\n/**/\n 3990,\n/**/\n 3989,\n/**/\n 3988,\n/**/\n 3987,\n/**/\n 3986,\n/**/\n 3985,\n/**/\n 3984,\n/**/\n 3983,\n/**/\n 3982,\n/**/\n 3981,\n/**/\n 3980,\n/**/\n 3979,\n/**/\n 3978,\n/**/\n 3977,\n/**/\n 3976,\n/**/\n 3975,\n/**/\n 3974,\n/**/\n 3973,\n/**/\n 3972,\n/**/\n 3971,\n/**/\n 3970,\n/**/\n 3969,\n/**/\n 3968,\n/**/\n 3967,\n/**/\n 3966,\n/**/\n 3965,\n/**/\n 3964,\n/**/\n 3963,\n/**/\n 3962,\n/**/\n 3961,\n/**/\n 3960,\n/**/\n 3959,\n/**/\n 3958,\n/**/\n 3957,\n/**/\n 3956,\n/**/\n 3955,\n/**/\n 3954,\n/**/\n 3953,\n/**/\n 3952,\n/**/\n 3951,\n/**/\n 3950,\n/**/\n 3949,\n/**/\n 3948,\n/**/\n 3947,\n/**/\n 3946,\n/**/\n 3945,\n/**/\n 3944,\n/**/\n 3943,\n/**/\n 3942,\n/**/\n 3941,\n/**/\n 3940,\n/**/\n 3939,\n/**/\n 3938,\n/**/\n 3937,\n/**/\n 3936,\n/**/\n 3935,\n/**/\n 3934,\n/**/\n 3933,\n/**/\n 3932,\n/**/\n 3931,\n/**/\n 3930,\n/**/\n 3929,\n/**/\n 3928,\n/**/\n 3927,\n/**/\n 3926,\n/**/\n 3925,\n/**/\n 3924,\n/**/\n 3923,\n/**/\n 3922,\n/**/\n 3921,\n/**/\n 3920,\n/**/\n 3919,\n/**/\n 3918,\n/**/\n 3917,\n/**/\n 3916,\n/**/\n 3915,\n/**/\n 3914,\n/**/\n 3913,\n/**/\n 3912,\n/**/\n 3911,\n/**/\n 3910,\n/**/\n 3909,\n/**/\n 3908,\n/**/\n 3907,\n/**/\n 3906,\n/**/\n 3905,\n/**/\n 3904,\n/**/\n 3903,\n/**/\n 3902,\n/**/\n 3901,\n/**/\n 3900,\n/**/\n 3899,\n/**/\n 3898,\n/**/\n 3897,\n/**/\n 3896,\n/**/\n 3895,\n/**/\n 3894,\n/**/\n 3893,\n/**/\n 3892,\n/**/\n 3891,\n/**/\n 3890,\n/**/\n 3889,\n/**/\n 3888,\n/**/\n 3887,\n/**/\n 3886,\n/**/\n 3885,\n/**/\n 3884,\n/**/\n 3883,\n/**/\n 3882,\n/**/\n 3881,\n/**/\n 3880,\n/**/\n 3879,\n/**/\n 3878,\n/**/\n 3877,\n/**/\n 3876,\n/**/\n 3875,\n/**/\n 3874,\n/**/\n 3873,\n/**/\n 3872,\n/**/\n 3871,\n/**/\n 3870,\n/**/\n 3869,\n/**/\n 3868,\n/**/\n 3867,\n/**/\n 3866,\n/**/\n 3865,\n/**/\n 3864,\n/**/\n 3863,\n/**/\n 3862,\n/**/\n 3861,\n/**/\n 3860,\n/**/\n 3859,\n/**/\n 3858,\n/**/\n 3857,\n/**/\n 3856,\n/**/\n 3855,\n/**/\n 3854,\n/**/\n 3853,\n/**/\n 3852,\n/**/\n 3851,\n/**/\n 3850,\n/**/\n 3849,\n/**/\n 3848,\n/**/\n 3847,\n/**/\n 3846,\n/**/\n 3845,\n/**/\n 3844,\n/**/\n 3843,\n/**/\n 3842,\n/**/\n 3841,\n/**/\n 3840,\n/**/\n 3839,\n/**/\n 3838,\n/**/\n 3837,\n/**/\n 3836,\n/**/\n 3835,\n/**/\n 3834,\n/**/\n 3833,\n/**/\n 3832,\n/**/\n 3831,\n/**/\n 3830,\n/**/\n 3829,\n/**/\n 3828,\n/**/\n 3827,\n/**/\n 3826,\n/**/\n 3825,\n/**/\n 3824,\n/**/\n 3823,\n/**/\n 3822,\n/**/\n 3821,\n/**/\n 3820,\n/**/\n 3819,\n/**/\n 3818,\n/**/\n 3817,\n/**/\n 3816,\n/**/\n 3815,\n/**/\n 3814,\n/**/\n 3813,\n/**/\n 3812,\n/**/\n 3811,\n/**/\n 3810,\n/**/\n 3809,\n/**/\n 3808,\n/**/\n 3807,\n/**/\n 3806,\n/**/\n 3805,\n/**/\n 3804,\n/**/\n 3803,\n/**/\n 3802,\n/**/\n 3801,\n/**/\n 3800,\n/**/\n 3799,\n/**/\n 3798,\n/**/\n 3797,\n/**/\n 3796,\n/**/\n 3795,\n/**/\n 3794,\n/**/\n 3793,\n/**/\n 3792,\n/**/\n 3791,\n/**/\n 3790,\n/**/\n 3789,\n/**/\n 3788,\n/**/\n 3787,\n/**/\n 3786,\n/**/\n 3785,\n/**/\n 3784,\n/**/\n 3783,\n/**/\n 3782,\n/**/\n 3781,\n/**/\n 3780,\n/**/\n 3779,\n/**/\n 3778,\n/**/\n 3777,\n/**/\n 3776,\n/**/\n 3775,\n/**/\n 3774,\n/**/\n 3773,\n/**/\n 3772,\n/**/\n 3771,\n/**/\n 3770,\n/**/\n 3769,\n/**/\n 3768,\n/**/\n 3767,\n/**/\n 3766,\n/**/\n 3765,\n/**/\n 3764,\n/**/\n 3763,\n/**/\n 3762,\n/**/\n 3761,\n/**/\n 3760,\n/**/\n 3759,\n/**/\n 3758,\n/**/\n 3757,\n/**/\n 3756,\n/**/\n 3755,\n/**/\n 3754,\n/**/\n 3753,\n/**/\n 3752,\n/**/\n 3751,\n/**/\n 3750,\n/**/\n 3749,\n/**/\n 3748,\n/**/\n 3747,\n/**/\n 3746,\n/**/\n 3745,\n/**/\n 3744,\n/**/\n 3743,\n/**/\n 3742,\n/**/\n 3741,\n/**/\n 3740,\n/**/\n 3739,\n/**/\n 3738,\n/**/\n 3737,\n/**/\n 3736,\n/**/\n 3735,\n/**/\n 3734,\n/**/\n 3733,\n/**/\n 3732,\n/**/\n 3731,\n/**/\n 3730,\n/**/\n 3729,\n/**/\n 3728,\n/**/\n 3727,\n/**/\n 3726,\n/**/\n 3725,\n/**/\n 3724,\n/**/\n 3723,\n/**/\n 3722,\n/**/\n 3721,\n/**/\n 3720,\n/**/\n 3719,\n/**/\n 3718,\n/**/\n 3717,\n/**/\n 3716,\n/**/\n 3715,\n/**/\n 3714,\n/**/\n 3713,\n/**/\n 3712,\n/**/\n 3711,\n/**/\n 3710,\n/**/\n 3709,\n/**/\n 3708,\n/**/\n 3707,\n/**/\n 3706,\n/**/\n 3705,\n/**/\n 3704,\n/**/\n 3703,\n/**/\n 3702,\n/**/\n 3701,\n/**/\n 3700,\n/**/\n 3699,\n/**/\n 3698,\n/**/\n 3697,\n/**/\n 3696,\n/**/\n 3695,\n/**/\n 3694,\n/**/\n 3693,\n/**/\n 3692,\n/**/\n 3691,\n/**/\n 3690,\n/**/\n 3689,\n/**/\n 3688,\n/**/\n 3687,\n/**/\n 3686,\n/**/\n 3685,\n/**/\n 3684,\n/**/\n 3683,\n/**/\n 3682,\n/**/\n 3681,\n/**/\n 3680,\n/**/\n 3679,\n/**/\n 3678,\n/**/\n 3677,\n/**/\n 3676,\n/**/\n 3675,\n/**/\n 3674,\n/**/\n 3673,\n/**/\n 3672,\n/**/\n 3671,\n/**/\n 3670,\n/**/\n 3669,\n/**/\n 3668,\n/**/\n 3667,\n/**/\n 3666,\n/**/\n 3665,\n/**/\n 3664,\n/**/\n 3663,\n/**/\n 3662,\n/**/\n 3661,\n/**/\n 3660,\n/**/\n 3659,\n/**/\n 3658,\n/**/\n 3657,\n/**/\n 3656,\n/**/\n 3655,\n/**/\n 3654,\n/**/\n 3653,\n/**/\n 3652,\n/**/\n 3651,\n/**/\n 3650,\n/**/\n 3649,\n/**/\n 3648,\n/**/\n 3647,\n/**/\n 3646,\n/**/\n 3645,\n/**/\n 3644,\n/**/\n 3643,\n/**/\n 3642,\n/**/\n 3641,\n/**/\n 3640,\n/**/\n 3639,\n/**/\n 3638,\n/**/\n 3637,\n/**/\n 3636,\n/**/\n 3635,\n/**/\n 3634,\n/**/\n 3633,\n/**/\n 3632,\n/**/\n 3631,\n/**/\n 3630,\n/**/\n 3629,\n/**/\n 3628,\n/**/\n 3627,\n/**/\n 3626,\n/**/\n 3625,\n/**/\n 3624,\n/**/\n 3623,\n/**/\n 3622,\n/**/\n 3621,\n/**/\n 3620,\n/**/\n 3619,\n/**/\n 3618,\n/**/\n 3617,\n/**/\n 3616,\n/**/\n 3615,\n/**/\n 3614,\n/**/\n 3613,\n/**/\n 3612,\n/**/\n 3611,\n/**/\n 3610,\n/**/\n 3609,\n/**/\n 3608,\n/**/\n 3607,\n/**/\n 3606,\n/**/\n 3605,\n/**/\n 3604,\n/**/\n 3603,\n/**/\n 3602,\n/**/\n 3601,\n/**/\n 3600,\n/**/\n 3599,\n/**/\n 3598,\n/**/\n 3597,\n/**/\n 3596,\n/**/\n 3595,\n/**/\n 3594,\n/**/\n 3593,\n/**/\n 3592,\n/**/\n 3591,\n/**/\n 3590,\n/**/\n 3589,\n/**/\n 3588,\n/**/\n 3587,\n/**/\n 3586,\n/**/\n 3585,\n/**/\n 3584,\n/**/\n 3583,\n/**/\n 3582,\n/**/\n 3581,\n/**/\n 3580,\n/**/\n 3579,\n/**/\n 3578,\n/**/\n 3577,\n/**/\n 3576,\n/**/\n 3575,\n/**/\n 3574,\n/**/\n 3573,\n/**/\n 3572,\n/**/\n 3571,\n/**/\n 3570,\n/**/\n 3569,\n/**/\n 3568,\n/**/\n 3567,\n/**/\n 3566,\n/**/\n 3565,\n/**/\n 3564,\n/**/\n 3563,\n/**/\n 3562,\n/**/\n 3561,\n/**/\n 3560,\n/**/\n 3559,\n/**/\n 3558,\n/**/\n 3557,\n/**/\n 3556,\n/**/\n 3555,\n/**/\n 3554,\n/**/\n 3553,\n/**/\n 3552,\n/**/\n 3551,\n/**/\n 3550,\n/**/\n 3549,\n/**/\n 3548,\n/**/\n 3547,\n/**/\n 3546,\n/**/\n 3545,\n/**/\n 3544,\n/**/\n 3543,\n/**/\n 3542,\n/**/\n 3541,\n/**/\n 3540,\n/**/\n 3539,\n/**/\n 3538,\n/**/\n 3537,\n/**/\n 3536,\n/**/\n 3535,\n/**/\n 3534,\n/**/\n 3533,\n/**/\n 3532,\n/**/\n 3531,\n/**/\n 3530,\n/**/\n 3529,\n/**/\n 3528,\n/**/\n 3527,\n/**/\n 3526,\n/**/\n 3525,\n/**/\n 3524,\n/**/\n 3523,\n/**/\n 3522,\n/**/\n 3521,\n/**/\n 3520,\n/**/\n 3519,\n/**/\n 3518,\n/**/\n 3517,\n/**/\n 3516,\n/**/\n 3515,\n/**/\n 3514,\n/**/\n 3513,\n/**/\n 3512,\n/**/\n 3511,\n/**/\n 3510,\n/**/\n 3509,\n/**/\n 3508,\n/**/\n 3507,\n/**/\n 3506,\n/**/\n 3505,\n/**/\n 3504,\n/**/\n 3503,\n/**/\n 3502,\n/**/\n 3501,\n/**/\n 3500,\n/**/\n 3499,\n/**/\n 3498,\n/**/\n 3497,\n/**/\n 3496,\n/**/\n 3495,\n/**/\n 3494,\n/**/\n 3493,\n/**/\n 3492,\n/**/\n 3491,\n/**/\n 3490,\n/**/\n 3489,\n/**/\n 3488,\n/**/\n 3487,\n/**/\n 3486,\n/**/\n 3485,\n/**/\n 3484,\n/**/\n 3483,\n/**/\n 3482,\n/**/\n 3481,\n/**/\n 3480,\n/**/\n 3479,\n/**/\n 3478,\n/**/\n 3477,\n/**/\n 3476,\n/**/\n 3475,\n/**/\n 3474,\n/**/\n 3473,\n/**/\n 3472,\n/**/\n 3471,\n/**/\n 3470,\n/**/\n 3469,\n/**/\n 3468,\n/**/\n 3467,\n/**/\n 3466,\n/**/\n 3465,\n/**/\n 3464,\n/**/\n 3463,\n/**/\n 3462,\n/**/\n 3461,\n/**/\n 3460,\n/**/\n 3459,\n/**/\n 3458,\n/**/\n 3457,\n/**/\n 3456,\n/**/\n 3455,\n/**/\n 3454,\n/**/\n 3453,\n/**/\n 3452,\n/**/\n 3451,\n/**/\n 3450,\n/**/\n 3449,\n/**/\n 3448,\n/**/\n 3447,\n/**/\n 3446,\n/**/\n 3445,\n/**/\n 3444,\n/**/\n 3443,\n/**/\n 3442,\n/**/\n 3441,\n/**/\n 3440,\n/**/\n 3439,\n/**/\n 3438,\n/**/\n 3437,\n/**/\n 3436,\n/**/\n 3435,\n/**/\n 3434,\n/**/\n 3433,\n/**/\n 3432,\n/**/\n 3431,\n/**/\n 3430,\n/**/\n 3429,\n/**/\n 3428,\n/**/\n 3427,\n/**/\n 3426,\n/**/\n 3425,\n/**/\n 3424,\n/**/\n 3423,\n/**/\n 3422,\n/**/\n 3421,\n/**/\n 3420,\n/**/\n 3419,\n/**/\n 3418,\n/**/\n 3417,\n/**/\n 3416,\n/**/\n 3415,\n/**/\n 3414,\n/**/\n 3413,\n/**/\n 3412,\n/**/\n 3411,\n/**/\n 3410,\n/**/\n 3409,\n/**/\n 3408,\n/**/\n 3407,\n/**/\n 3406,\n/**/\n 3405,\n/**/\n 3404,\n/**/\n 3403,\n/**/\n 3402,\n/**/\n 3401,\n/**/\n 3400,\n/**/\n 3399,\n/**/\n 3398,\n/**/\n 3397,\n/**/\n 3396,\n/**/\n 3395,\n/**/\n 3394,\n/**/\n 3393,\n/**/\n 3392,\n/**/\n 3391,\n/**/\n 3390,\n/**/\n 3389,\n/**/\n 3388,\n/**/\n 3387,\n/**/\n 3386,\n/**/\n 3385,\n/**/\n 3384,\n/**/\n 3383,\n/**/\n 3382,\n/**/\n 3381,\n/**/\n 3380,\n/**/\n 3379,\n/**/\n 3378,\n/**/\n 3377,\n/**/\n 3376,\n/**/\n 3375,\n/**/\n 3374,\n/**/\n 3373,\n/**/\n 3372,\n/**/\n 3371,\n/**/\n 3370,\n/**/\n 3369,\n/**/\n 3368,\n/**/\n 3367,\n/**/\n 3366,\n/**/\n 3365,\n/**/\n 3364,\n/**/\n 3363,\n/**/\n 3362,\n/**/\n 3361,\n/**/\n 3360,\n/**/\n 3359,\n/**/\n 3358,\n/**/\n 3357,\n/**/\n 3356,\n/**/\n 3355,\n/**/\n 3354,\n/**/\n 3353,\n/**/\n 3352,\n/**/\n 3351,\n/**/\n 3350,\n/**/\n 3349,\n/**/\n 3348,\n/**/\n 3347,\n/**/\n 3346,\n/**/\n 3345,\n/**/\n 3344,\n/**/\n 3343,\n/**/\n 3342,\n/**/\n 3341,\n/**/\n 3340,\n/**/\n 3339,\n/**/\n 3338,\n/**/\n 3337,\n/**/\n 3336,\n/**/\n 3335,\n/**/\n 3334,\n/**/\n 3333,\n/**/\n 3332,\n/**/\n 3331,\n/**/\n 3330,\n/**/\n 3329,\n/**/\n 3328,\n/**/\n 3327,\n/**/\n 3326,\n/**/\n 3325,\n/**/\n 3324,\n/**/\n 3323,\n/**/\n 3322,\n/**/\n 3321,\n/**/\n 3320,\n/**/\n 3319,\n/**/\n 3318,\n/**/\n 3317,\n/**/\n 3316,\n/**/\n 3315,\n/**/\n 3314,\n/**/\n 3313,\n/**/\n 3312,\n/**/\n 3311,\n/**/\n 3310,\n/**/\n 3309,\n/**/\n 3308,\n/**/\n 3307,\n/**/\n 3306,\n/**/\n 3305,\n/**/\n 3304,\n/**/\n 3303,\n/**/\n 3302,\n/**/\n 3301,\n/**/\n 3300,\n/**/\n 3299,\n/**/\n 3298,\n/**/\n 3297,\n/**/\n 3296,\n/**/\n 3295,\n/**/\n 3294,\n/**/\n 3293,\n/**/\n 3292,\n/**/\n 3291,\n/**/\n 3290,\n/**/\n 3289,\n/**/\n 3288,\n/**/\n 3287,\n/**/\n 3286,\n/**/\n 3285,\n/**/\n 3284,\n/**/\n 3283,\n/**/\n 3282,\n/**/\n 3281,\n/**/\n 3280,\n/**/\n 3279,\n/**/\n 3278,\n/**/\n 3277,\n/**/\n 3276,\n/**/\n 3275,\n/**/\n 3274,\n/**/\n 3273,\n/**/\n 3272,\n/**/\n 3271,\n/**/\n 3270,\n/**/\n 3269,\n/**/\n 3268,\n/**/\n 3267,\n/**/\n 3266,\n/**/\n 3265,\n/**/\n 3264,\n/**/\n 3263,\n/**/\n 3262,\n/**/\n 3261,\n/**/\n 3260,\n/**/\n 3259,\n/**/\n 3258,\n/**/\n 3257,\n/**/\n 3256,\n/**/\n 3255,\n/**/\n 3254,\n/**/\n 3253,\n/**/\n 3252,\n/**/\n 3251,\n/**/\n 3250,\n/**/\n 3249,\n/**/\n 3248,\n/**/\n 3247,\n/**/\n 3246,\n/**/\n 3245,\n/**/\n 3244,\n/**/\n 3243,\n/**/\n 3242,\n/**/\n 3241,\n/**/\n 3240,\n/**/\n 3239,\n/**/\n 3238,\n/**/\n 3237,\n/**/\n 3236,\n/**/\n 3235,\n/**/\n 3234,\n/**/\n 3233,\n/**/\n 3232,\n/**/\n 3231,\n/**/\n 3230,\n/**/\n 3229,\n/**/\n 3228,\n/**/\n 3227,\n/**/\n 3226,\n/**/\n 3225,\n/**/\n 3224,\n/**/\n 3223,\n/**/\n 3222,\n/**/\n 3221,\n/**/\n 3220,\n/**/\n 3219,\n/**/\n 3218,\n/**/\n 3217,\n/**/\n 3216,\n/**/\n 3215,\n/**/\n 3214,\n/**/\n 3213,\n/**/\n 3212,\n/**/\n 3211,\n/**/\n 3210,\n/**/\n 3209,\n/**/\n 3208,\n/**/\n 3207,\n/**/\n 3206,\n/**/\n 3205,\n/**/\n 3204,\n/**/\n 3203,\n/**/\n 3202,\n/**/\n 3201,\n/**/\n 3200,\n/**/\n 3199,\n/**/\n 3198,\n/**/\n 3197,\n/**/\n 3196,\n/**/\n 3195,\n/**/\n 3194,\n/**/\n 3193,\n/**/\n 3192,\n/**/\n 3191,\n/**/\n 3190,\n/**/\n 3189,\n/**/\n 3188,\n/**/\n 3187,\n/**/\n 3186,\n/**/\n 3185,\n/**/\n 3184,\n/**/\n 3183,\n/**/\n 3182,\n/**/\n 3181,\n/**/\n 3180,\n/**/\n 3179,\n/**/\n 3178,\n/**/\n 3177,\n/**/\n 3176,\n/**/\n 3175,\n/**/\n 3174,\n/**/\n 3173,\n/**/\n 3172,\n/**/\n 3171,\n/**/\n 3170,\n/**/\n 3169,\n/**/\n 3168,\n/**/\n 3167,\n/**/\n 3166,\n/**/\n 3165,\n/**/\n 3164,\n/**/\n 3163,\n/**/\n 3162,\n/**/\n 3161,\n/**/\n 3160,\n/**/\n 3159,\n/**/\n 3158,\n/**/\n 3157,\n/**/\n 3156,\n/**/\n 3155,\n/**/\n 3154,\n/**/\n 3153,\n/**/\n 3152,\n/**/\n 3151,\n/**/\n 3150,\n/**/\n 3149,\n/**/\n 3148,\n/**/\n 3147,\n/**/\n 3146,\n/**/\n 3145,\n/**/\n 3144,\n/**/\n 3143,\n/**/\n 3142,\n/**/\n 3141,\n/**/\n 3140,\n/**/\n 3139,\n/**/\n 3138,\n/**/\n 3137,\n/**/\n 3136,\n/**/\n 3135,\n/**/\n 3134,\n/**/\n 3133,\n/**/\n 3132,\n/**/\n 3131,\n/**/\n 3130,\n/**/\n 3129,\n/**/\n 3128,\n/**/\n 3127,\n/**/\n 3126,\n/**/\n 3125,\n/**/\n 3124,\n/**/\n 3123,\n/**/\n 3122,\n/**/\n 3121,\n/**/\n 3120,\n/**/\n 3119,\n/**/\n 3118,\n/**/\n 3117,\n/**/\n 3116,\n/**/\n 3115,\n/**/\n 3114,\n/**/\n 3113,\n/**/\n 3112,\n/**/\n 3111,\n/**/\n 3110,\n/**/\n 3109,\n/**/\n 3108,\n/**/\n 3107,\n/**/\n 3106,\n/**/\n 3105,\n/**/\n 3104,\n/**/\n 3103,\n/**/\n 3102,\n/**/\n 3101,\n/**/\n 3100,\n/**/\n 3099,\n/**/\n 3098,\n/**/\n 3097,\n/**/\n 3096,\n/**/\n 3095,\n/**/\n 3094,\n/**/\n 3093,\n/**/\n 3092,\n/**/\n 3091,\n/**/\n 3090,\n/**/\n 3089,\n/**/\n 3088,\n/**/\n 3087,\n/**/\n 3086,\n/**/\n 3085,\n/**/\n 3084,\n/**/\n 3083,\n/**/\n 3082,\n/**/\n 3081,\n/**/\n 3080,\n/**/\n 3079,\n/**/\n 3078,\n/**/\n 3077,\n/**/\n 3076,\n/**/\n 3075,\n/**/\n 3074,\n/**/\n 3073,\n/**/\n 3072,\n/**/\n 3071,\n/**/\n 3070,\n/**/\n 3069,\n/**/\n 3068,\n/**/\n 3067,\n/**/\n 3066,\n/**/\n 3065,\n/**/\n 3064,\n/**/\n 3063,\n/**/\n 3062,\n/**/\n 3061,\n/**/\n 3060,\n/**/\n 3059,\n/**/\n 3058,\n/**/\n 3057,\n/**/\n 3056,\n/**/\n 3055,\n/**/\n 3054,\n/**/\n 3053,\n/**/\n 3052,\n/**/\n 3051,\n/**/\n 3050,\n/**/\n 3049,\n/**/\n 3048,\n/**/\n 3047,\n/**/\n 3046,\n/**/\n 3045,\n/**/\n 3044,\n/**/\n 3043,\n/**/\n 3042,\n/**/\n 3041,\n/**/\n 3040,\n/**/\n 3039,\n/**/\n 3038,\n/**/\n 3037,\n/**/\n 3036,\n/**/\n 3035,\n/**/\n 3034,\n/**/\n 3033,\n/**/\n 3032,\n/**/\n 3031,\n/**/\n 3030,\n/**/\n 3029,\n/**/\n 3028,\n/**/\n 3027,\n/**/\n 3026,\n/**/\n 3025,\n/**/\n 3024,\n/**/\n 3023,\n/**/\n 3022,\n/**/\n 3021,\n/**/\n 3020,\n/**/\n 3019,\n/**/\n 3018,\n/**/\n 3017,\n/**/\n 3016,\n/**/\n 3015,\n/**/\n 3014,\n/**/\n 3013,\n/**/\n 3012,\n/**/\n 3011,\n/**/\n 3010,\n/**/\n 3009,\n/**/\n 3008,\n/**/\n 3007,\n/**/\n 3006,\n/**/\n 3005,\n/**/\n 3004,\n/**/\n 3003,\n/**/\n 3002,\n/**/\n 3001,\n/**/\n 3000,\n/**/\n 2999,\n/**/\n 2998,\n/**/\n 2997,\n/**/\n 2996,\n/**/\n 2995,\n/**/\n 2994,\n/**/\n 2993,\n/**/\n 2992,\n/**/\n 2991,\n/**/\n 2990,\n/**/\n 2989,\n/**/\n 2988,\n/**/\n 2987,\n/**/\n 2986,\n/**/\n 2985,\n/**/\n 2984,\n/**/\n 2983,\n/**/\n 2982,\n/**/\n 2981,\n/**/\n 2980,\n/**/\n 2979,\n/**/\n 2978,\n/**/\n 2977,\n/**/\n 2976,\n/**/\n 2975,\n/**/\n 2974,\n/**/\n 2973,\n/**/\n 2972,\n/**/\n 2971,\n/**/\n 2970,\n/**/\n 2969,\n/**/\n 2968,\n/**/\n 2967,\n/**/\n 2966,\n/**/\n 2965,\n/**/\n 2964,\n/**/\n 2963,\n/**/\n 2962,\n/**/\n 2961,\n/**/\n 2960,\n/**/\n 2959,\n/**/\n 2958,\n/**/\n 2957,\n/**/\n 2956,\n/**/\n 2955,\n/**/\n 2954,\n/**/\n 2953,\n/**/\n 2952,\n/**/\n 2951,\n/**/\n 2950,\n/**/\n 2949,\n/**/\n 2948,\n/**/\n 2947,\n/**/\n 2946,\n/**/\n 2945,\n/**/\n 2944,\n/**/\n 2943,\n/**/\n 2942,\n/**/\n 2941,\n/**/\n 2940,\n/**/\n 2939,\n/**/\n 2938,\n/**/\n 2937,\n/**/\n 2936,\n/**/\n 2935,\n/**/\n 2934,\n/**/\n 2933,\n/**/\n 2932,\n/**/\n 2931,\n/**/\n 2930,\n/**/\n 2929,\n/**/\n 2928,\n/**/\n 2927,\n/**/\n 2926,\n/**/\n 2925,\n/**/\n 2924,\n/**/\n 2923,\n/**/\n 2922,\n/**/\n 2921,\n/**/\n 2920,\n/**/\n 2919,\n/**/\n 2918,\n/**/\n 2917,\n/**/\n 2916,\n/**/\n 2915,\n/**/\n 2914,\n/**/\n 2913,\n/**/\n 2912,\n/**/\n 2911,\n/**/\n 2910,\n/**/\n 2909,\n/**/\n 2908,\n/**/\n 2907,\n/**/\n 2906,\n/**/\n 2905,\n/**/\n 2904,\n/**/\n 2903,\n/**/\n 2902,\n/**/\n 2901,\n/**/\n 2900,\n/**/\n 2899,\n/**/\n 2898,\n/**/\n 2897,\n/**/\n 2896,\n/**/\n 2895,\n/**/\n 2894,\n/**/\n 2893,\n/**/\n 2892,\n/**/\n 2891,\n/**/\n 2890,\n/**/\n 2889,\n/**/\n 2888,\n/**/\n 2887,\n/**/\n 2886,\n/**/\n 2885,\n/**/\n 2884,\n/**/\n 2883,\n/**/\n 2882,\n/**/\n 2881,\n/**/\n 2880,\n/**/\n 2879,\n/**/\n 2878,\n/**/\n 2877,\n/**/\n 2876,\n/**/\n 2875,\n/**/\n 2874,\n/**/\n 2873,\n/**/\n 2872,\n/**/\n 2871,\n/**/\n 2870,\n/**/\n 2869,\n/**/\n 2868,\n/**/\n 2867,\n/**/\n 2866,\n/**/\n 2865,\n/**/\n 2864,\n/**/\n 2863,\n/**/\n 2862,\n/**/\n 2861,\n/**/\n 2860,\n/**/\n 2859,\n/**/\n 2858,\n/**/\n 2857,\n/**/\n 2856,\n/**/\n 2855,\n/**/\n 2854,\n/**/\n 2853,\n/**/\n 2852,\n/**/\n 2851,\n/**/\n 2850,\n/**/\n 2849,\n/**/\n 2848,\n/**/\n 2847,\n/**/\n 2846,\n/**/\n 2845,\n/**/\n 2844,\n/**/\n 2843,\n/**/\n 2842,\n/**/\n 2841,\n/**/\n 2840,\n/**/\n 2839,\n/**/\n 2838,\n/**/\n 2837,\n/**/\n 2836,\n/**/\n 2835,\n/**/\n 2834,\n/**/\n 2833,\n/**/\n 2832,\n/**/\n 2831,\n/**/\n 2830,\n/**/\n 2829,\n/**/\n 2828,\n/**/\n 2827,\n/**/\n 2826,\n/**/\n 2825,\n/**/\n 2824,\n/**/\n 2823,\n/**/\n 2822,\n/**/\n 2821,\n/**/\n 2820,\n/**/\n 2819,\n/**/\n 2818,\n/**/\n 2817,\n/**/\n 2816,\n/**/\n 2815,\n/**/\n 2814,\n/**/\n 2813,\n/**/\n 2812,\n/**/\n 2811,\n/**/\n 2810,\n/**/\n 2809,\n/**/\n 2808,\n/**/\n 2807,\n/**/\n 2806,\n/**/\n 2805,\n/**/\n 2804,\n/**/\n 2803,\n/**/\n 2802,\n/**/\n 2801,\n/**/\n 2800,\n/**/\n 2799,\n/**/\n 2798,\n/**/\n 2797,\n/**/\n 2796,\n/**/\n 2795,\n/**/\n 2794,\n/**/\n 2793,\n/**/\n 2792,\n/**/\n 2791,\n/**/\n 2790,\n/**/\n 2789,\n/**/\n 2788,\n/**/\n 2787,\n/**/\n 2786,\n/**/\n 2785,\n/**/\n 2784,\n/**/\n 2783,\n/**/\n 2782,\n/**/\n 2781,\n/**/\n 2780,\n/**/\n 2779,\n/**/\n 2778,\n/**/\n 2777,\n/**/\n 2776,\n/**/\n 2775,\n/**/\n 2774,\n/**/\n 2773,\n/**/\n 2772,\n/**/\n 2771,\n/**/\n 2770,\n/**/\n 2769,\n/**/\n 2768,\n/**/\n 2767,\n/**/\n 2766,\n/**/\n 2765,\n/**/\n 2764,\n/**/\n 2763,\n/**/\n 2762,\n/**/\n 2761,\n/**/\n 2760,\n/**/\n 2759,\n/**/\n 2758,\n/**/\n 2757,\n/**/\n 2756,\n/**/\n 2755,\n/**/\n 2754,\n/**/\n 2753,\n/**/\n 2752,\n/**/\n 2751,\n/**/\n 2750,\n/**/\n 2749,\n/**/\n 2748,\n/**/\n 2747,\n/**/\n 2746,\n/**/\n 2745,\n/**/\n 2744,\n/**/\n 2743,\n/**/\n 2742,\n/**/\n 2741,\n/**/\n 2740,\n/**/\n 2739,\n/**/\n 2738,\n/**/\n 2737,\n/**/\n 2736,\n/**/\n 2735,\n/**/\n 2734,\n/**/\n 2733,\n/**/\n 2732,\n/**/\n 2731,\n/**/\n 2730,\n/**/\n 2729,\n/**/\n 2728,\n/**/\n 2727,\n/**/\n 2726,\n/**/\n 2725,\n/**/\n 2724,\n/**/\n 2723,\n/**/\n 2722,\n/**/\n 2721,\n/**/\n 2720,\n/**/\n 2719,\n/**/\n 2718,\n/**/\n 2717,\n/**/\n 2716,\n/**/\n 2715,\n/**/\n 2714,\n/**/\n 2713,\n/**/\n 2712,\n/**/\n 2711,\n/**/\n 2710,\n/**/\n 2709,\n/**/\n 2708,\n/**/\n 2707,\n/**/\n 2706,\n/**/\n 2705,\n/**/\n 2704,\n/**/\n 2703,\n/**/\n 2702,\n/**/\n 2701,\n/**/\n 2700,\n/**/\n 2699,\n/**/\n 2698,\n/**/\n 2697,\n/**/\n 2696,\n/**/\n 2695,\n/**/\n 2694,\n/**/\n 2693,\n/**/\n 2692,\n/**/\n 2691,\n/**/\n 2690,\n/**/\n 2689,\n/**/\n 2688,\n/**/\n 2687,\n/**/\n 2686,\n/**/\n 2685,\n/**/\n 2684,\n/**/\n 2683,\n/**/\n 2682,\n/**/\n 2681,\n/**/\n 2680,\n/**/\n 2679,\n/**/\n 2678,\n/**/\n 2677,\n/**/\n 2676,\n/**/\n 2675,\n/**/\n 2674,\n/**/\n 2673,\n/**/\n 2672,\n/**/\n 2671,\n/**/\n 2670,\n/**/\n 2669,\n/**/\n 2668,\n/**/\n 2667,\n/**/\n 2666,\n/**/\n 2665,\n/**/\n 2664,\n/**/\n 2663,\n/**/\n 2662,\n/**/\n 2661,\n/**/\n 2660,\n/**/\n 2659,\n/**/\n 2658,\n/**/\n 2657,\n/**/\n 2656,\n/**/\n 2655,\n/**/\n 2654,\n/**/\n 2653,\n/**/\n 2652,\n/**/\n 2651,\n/**/\n 2650,\n/**/\n 2649,\n/**/\n 2648,\n/**/\n 2647,\n/**/\n 2646,\n/**/\n 2645,\n/**/\n 2644,\n/**/\n 2643,\n/**/\n 2642,\n/**/\n 2641,\n/**/\n 2640,\n/**/\n 2639,\n/**/\n 2638,\n/**/\n 2637,\n/**/\n 2636,\n/**/\n 2635,\n/**/\n 2634,\n/**/\n 2633,\n/**/\n 2632,\n/**/\n 2631,\n/**/\n 2630,\n/**/\n 2629,\n/**/\n 2628,\n/**/\n 2627,\n/**/\n 2626,\n/**/\n 2625,\n/**/\n 2624,\n/**/\n 2623,\n/**/\n 2622,\n/**/\n 2621,\n/**/\n 2620,\n/**/\n 2619,\n/**/\n 2618,\n/**/\n 2617,\n/**/\n 2616,\n/**/\n 2615,\n/**/\n 2614,\n/**/\n 2613,\n/**/\n 2612,\n/**/\n 2611,\n/**/\n 2610,\n/**/\n 2609,\n/**/\n 2608,\n/**/\n 2607,\n/**/\n 2606,\n/**/\n 2605,\n/**/\n 2604,\n/**/\n 2603,\n/**/\n 2602,\n/**/\n 2601,\n/**/\n 2600,\n/**/\n 2599,\n/**/\n 2598,\n/**/\n 2597,\n/**/\n 2596,\n/**/\n 2595,\n/**/\n 2594,\n/**/\n 2593,\n/**/\n 2592,\n/**/\n 2591,\n/**/\n 2590,\n/**/\n 2589,\n/**/\n 2588,\n/**/\n 2587,\n/**/\n 2586,\n/**/\n 2585,\n/**/\n 2584,\n/**/\n 2583,\n/**/\n 2582,\n/**/\n 2581,\n/**/\n 2580,\n/**/\n 2579,\n/**/\n 2578,\n/**/\n 2577,\n/**/\n 2576,\n/**/\n 2575,\n/**/\n 2574,\n/**/\n 2573,\n/**/\n 2572,\n/**/\n 2571,\n/**/\n 2570,\n/**/\n 2569,\n/**/\n 2568,\n/**/\n 2567,\n/**/\n 2566,\n/**/\n 2565,\n/**/\n 2564,\n/**/\n 2563,\n/**/\n 2562,\n/**/\n 2561,\n/**/\n 2560,\n/**/\n 2559,\n/**/\n 2558,\n/**/\n 2557,\n/**/\n 2556,\n/**/\n 2555,\n/**/\n 2554,\n/**/\n 2553,\n/**/\n 2552,\n/**/\n 2551,\n/**/\n 2550,\n/**/\n 2549,\n/**/\n 2548,\n/**/\n 2547,\n/**/\n 2546,\n/**/\n 2545,\n/**/\n 2544,\n/**/\n 2543,\n/**/\n 2542,\n/**/\n 2541,\n/**/\n 2540,\n/**/\n 2539,\n/**/\n 2538,\n/**/\n 2537,\n/**/\n 2536,\n/**/\n 2535,\n/**/\n 2534,\n/**/\n 2533,\n/**/\n 2532,\n/**/\n 2531,\n/**/\n 2530,\n/**/\n 2529,\n/**/\n 2528,\n/**/\n 2527,\n/**/\n 2526,\n/**/\n 2525,\n/**/\n 2524,\n/**/\n 2523,\n/**/\n 2522,\n/**/\n 2521,\n/**/\n 2520,\n/**/\n 2519,\n/**/\n 2518,\n/**/\n 2517,\n/**/\n 2516,\n/**/\n 2515,\n/**/\n 2514,\n/**/\n 2513,\n/**/\n 2512,\n/**/\n 2511,\n/**/\n 2510,\n/**/\n 2509,\n/**/\n 2508,\n/**/\n 2507,\n/**/\n 2506,\n/**/\n 2505,\n/**/\n 2504,\n/**/\n 2503,\n/**/\n 2502,\n/**/\n 2501,\n/**/\n 2500,\n/**/\n 2499,\n/**/\n 2498,\n/**/\n 2497,\n/**/\n 2496,\n/**/\n 2495,\n/**/\n 2494,\n/**/\n 2493,\n/**/\n 2492,\n/**/\n 2491,\n/**/\n 2490,\n/**/\n 2489,\n/**/\n 2488,\n/**/\n 2487,\n/**/\n 2486,\n/**/\n 2485,\n/**/\n 2484,\n/**/\n 2483,\n/**/\n 2482,\n/**/\n 2481,\n/**/\n 2480,\n/**/\n 2479,\n/**/\n 2478,\n/**/\n 2477,\n/**/\n 2476,\n/**/\n 2475,\n/**/\n 2474,\n/**/\n 2473,\n/**/\n 2472,\n/**/\n 2471,\n/**/\n 2470,\n/**/\n 2469,\n/**/\n 2468,\n/**/\n 2467,\n/**/\n 2466,\n/**/\n 2465,\n/**/\n 2464,\n/**/\n 2463,\n/**/\n 2462,\n/**/\n 2461,\n/**/\n 2460,\n/**/\n 2459,\n/**/\n 2458,\n/**/\n 2457,\n/**/\n 2456,\n/**/\n 2455,\n/**/\n 2454,\n/**/\n 2453,\n/**/\n 2452,\n/**/\n 2451,\n/**/\n 2450,\n/**/\n 2449,\n/**/\n 2448,\n/**/\n 2447,\n/**/\n 2446,\n/**/\n 2445,\n/**/\n 2444,\n/**/\n 2443,\n/**/\n 2442,\n/**/\n 2441,\n/**/\n 2440,\n/**/\n 2439,\n/**/\n 2438,\n/**/\n 2437,\n/**/\n 2436,\n/**/\n 2435,\n/**/\n 2434,\n/**/\n 2433,\n/**/\n 2432,\n/**/\n 2431,\n/**/\n 2430,\n/**/\n 2429,\n/**/\n 2428,\n/**/\n 2427,\n/**/\n 2426,\n/**/\n 2425,\n/**/\n 2424,\n/**/\n 2423,\n/**/\n 2422,\n/**/\n 2421,\n/**/\n 2420,\n/**/\n 2419,\n/**/\n 2418,\n/**/\n 2417,\n/**/\n 2416,\n/**/\n 2415,\n/**/\n 2414,\n/**/\n 2413,\n/**/\n 2412,\n/**/\n 2411,\n/**/\n 2410,\n/**/\n 2409,\n/**/\n 2408,\n/**/\n 2407,\n/**/\n 2406,\n/**/\n 2405,\n/**/\n 2404,\n/**/\n 2403,\n/**/\n 2402,\n/**/\n 2401,\n/**/\n 2400,\n/**/\n 2399,\n/**/\n 2398,\n/**/\n 2397,\n/**/\n 2396,\n/**/\n 2395,\n/**/\n 2394,\n/**/\n 2393,\n/**/\n 2392,\n/**/\n 2391,\n/**/\n 2390,\n/**/\n 2389,\n/**/\n 2388,\n/**/\n 2387,\n/**/\n 2386,\n/**/\n 2385,\n/**/\n 2384,\n/**/\n 2383,\n/**/\n 2382,\n/**/\n 2381,\n/**/\n 2380,\n/**/\n 2379,\n/**/\n 2378,\n/**/\n 2377,\n/**/\n 2376,\n/**/\n 2375,\n/**/\n 2374,\n/**/\n 2373,\n/**/\n 2372,\n/**/\n 2371,\n/**/\n 2370,\n/**/\n 2369,\n/**/\n 2368,\n/**/\n 2367,\n/**/\n 2366,\n/**/\n 2365,\n/**/\n 2364,\n/**/\n 2363,\n/**/\n 2362,\n/**/\n 2361,\n/**/\n 2360,\n/**/\n 2359,\n/**/\n 2358,\n/**/\n 2357,\n/**/\n 2356,\n/**/\n 2355,\n/**/\n 2354,\n/**/\n 2353,\n/**/\n 2352,\n/**/\n 2351,\n/**/\n 2350,\n/**/\n 2349,\n/**/\n 2348,\n/**/\n 2347,\n/**/\n 2346,\n/**/\n 2345,\n/**/\n 2344,\n/**/\n 2343,\n/**/\n 2342,\n/**/\n 2341,\n/**/\n 2340,\n/**/\n 2339,\n/**/\n 2338,\n/**/\n 2337,\n/**/\n 2336,\n/**/\n 2335,\n/**/\n 2334,\n/**/\n 2333,\n/**/\n 2332,\n/**/\n 2331,\n/**/\n 2330,\n/**/\n 2329,\n/**/\n 2328,\n/**/\n 2327,\n/**/\n 2326,\n/**/\n 2325,\n/**/\n 2324,\n/**/\n 2323,\n/**/\n 2322,\n/**/\n 2321,\n/**/\n 2320,\n/**/\n 2319,\n/**/\n 2318,\n/**/\n 2317,\n/**/\n 2316,\n/**/\n 2315,\n/**/\n 2314,\n/**/\n 2313,\n/**/\n 2312,\n/**/\n 2311,\n/**/\n 2310,\n/**/\n 2309,\n/**/\n 2308,\n/**/\n 2307,\n/**/\n 2306,\n/**/\n 2305,\n/**/\n 2304,\n/**/\n 2303,\n/**/\n 2302,\n/**/\n 2301,\n/**/\n 2300,\n/**/\n 2299,\n/**/\n 2298,\n/**/\n 2297,\n/**/\n 2296,\n/**/\n 2295,\n/**/\n 2294,\n/**/\n 2293,\n/**/\n 2292,\n/**/\n 2291,\n/**/\n 2290,\n/**/\n 2289,\n/**/\n 2288,\n/**/\n 2287,\n/**/\n 2286,\n/**/\n 2285,\n/**/\n 2284,\n/**/\n 2283,\n/**/\n 2282,\n/**/\n 2281,\n/**/\n 2280,\n/**/\n 2279,\n/**/\n 2278,\n/**/\n 2277,\n/**/\n 2276,\n/**/\n 2275,\n/**/\n 2274,\n/**/\n 2273,\n/**/\n 2272,\n/**/\n 2271,\n/**/\n 2270,\n/**/\n 2269,\n/**/\n 2268,\n/**/\n 2267,\n/**/\n 2266,\n/**/\n 2265,\n/**/\n 2264,\n/**/\n 2263,\n/**/\n 2262,\n/**/\n 2261,\n/**/\n 2260,\n/**/\n 2259,\n/**/\n 2258,\n/**/\n 2257,\n/**/\n 2256,\n/**/\n 2255,\n/**/\n 2254,\n/**/\n 2253,\n/**/\n 2252,\n/**/\n 2251,\n/**/\n 2250,\n/**/\n 2249,\n/**/\n 2248,\n/**/\n 2247,\n/**/\n 2246,\n/**/\n 2245,\n/**/\n 2244,\n/**/\n 2243,\n/**/\n 2242,\n/**/\n 2241,\n/**/\n 2240,\n/**/\n 2239,\n/**/\n 2238,\n/**/\n 2237,\n/**/\n 2236,\n/**/\n 2235,\n/**/\n 2234,\n/**/\n 2233,\n/**/\n 2232,\n/**/\n 2231,\n/**/\n 2230,\n/**/\n 2229,\n/**/\n 2228,\n/**/\n 2227,\n/**/\n 2226,\n/**/\n 2225,\n/**/\n 2224,\n/**/\n 2223,\n/**/\n 2222,\n/**/\n 2221,\n/**/\n 2220,\n/**/\n 2219,\n/**/\n 2218,\n/**/\n 2217,\n/**/\n 2216,\n/**/\n 2215,\n/**/\n 2214,\n/**/\n 2213,\n/**/\n 2212,\n/**/\n 2211,\n/**/\n 2210,\n/**/\n 2209,\n/**/\n 2208,\n/**/\n 2207,\n/**/\n 2206,\n/**/\n 2205,\n/**/\n 2204,\n/**/\n 2203,\n/**/\n 2202,\n/**/\n 2201,\n/**/\n 2200,\n/**/\n 2199,\n/**/\n 2198,\n/**/\n 2197,\n/**/\n 2196,\n/**/\n 2195,\n/**/\n 2194,\n/**/\n 2193,\n/**/\n 2192,\n/**/\n 2191,\n/**/\n 2190,\n/**/\n 2189,\n/**/\n 2188,\n/**/\n 2187,\n/**/\n 2186,\n/**/\n 2185,\n/**/\n 2184,\n/**/\n 2183,\n/**/\n 2182,\n/**/\n 2181,\n/**/\n 2180,\n/**/\n 2179,\n/**/\n 2178,\n/**/\n 2177,\n/**/\n 2176,\n/**/\n 2175,\n/**/\n 2174,\n/**/\n 2173,\n/**/\n 2172,\n/**/\n 2171,\n/**/\n 2170,\n/**/\n 2169,\n/**/\n 2168,\n/**/\n 2167,\n/**/\n 2166,\n/**/\n 2165,\n/**/\n 2164,\n/**/\n 2163,\n/**/\n 2162,\n/**/\n 2161,\n/**/\n 2160,\n/**/\n 2159,\n/**/\n 2158,\n/**/\n 2157,\n/**/\n 2156,\n/**/\n 2155,\n/**/\n 2154,\n/**/\n 2153,\n/**/\n 2152,\n/**/\n 2151,\n/**/\n 2150,\n/**/\n 2149,\n/**/\n 2148,\n/**/\n 2147,\n/**/\n 2146,\n/**/\n 2145,\n/**/\n 2144,\n/**/\n 2143,\n/**/\n 2142,\n/**/\n 2141,\n/**/\n 2140,\n/**/\n 2139,\n/**/\n 2138,\n/**/\n 2137,\n/**/\n 2136,\n/**/\n 2135,\n/**/\n 2134,\n/**/\n 2133,\n/**/\n 2132,\n/**/\n 2131,\n/**/\n 2130,\n/**/\n 2129,\n/**/\n 2128,\n/**/\n 2127,\n/**/\n 2126,\n/**/\n 2125,\n/**/\n 2124,\n/**/\n 2123,\n/**/\n 2122,\n/**/\n 2121,\n/**/\n 2120,\n/**/\n 2119,\n/**/\n 2118,\n/**/\n 2117,\n/**/\n 2116,\n/**/\n 2115,\n/**/\n 2114,\n/**/\n 2113,\n/**/\n 2112,\n/**/\n 2111,\n/**/\n 2110,\n/**/\n 2109,\n/**/\n 2108,\n/**/\n 2107,\n/**/\n 2106,\n/**/\n 2105,\n/**/\n 2104,\n/**/\n 2103,\n/**/\n 2102,\n/**/\n 2101,\n/**/\n 2100,\n/**/\n 2099,\n/**/\n 2098,\n/**/\n 2097,\n/**/\n 2096,\n/**/\n 2095,\n/**/\n 2094,\n/**/\n 2093,\n/**/\n 2092,\n/**/\n 2091,\n/**/\n 2090,\n/**/\n 2089,\n/**/\n 2088,\n/**/\n 2087,\n/**/\n 2086,\n/**/\n 2085,\n/**/\n 2084,\n/**/\n 2083,\n/**/\n 2082,\n/**/\n 2081,\n/**/\n 2080,\n/**/\n 2079,\n/**/\n 2078,\n/**/\n 2077,\n/**/\n 2076,\n/**/\n 2075,\n/**/\n 2074,\n/**/\n 2073,\n/**/\n 2072,\n/**/\n 2071,\n/**/\n 2070,\n/**/\n 2069,\n/**/\n 2068,\n/**/\n 2067,\n/**/\n 2066,\n/**/\n 2065,\n/**/\n 2064,\n/**/\n 2063,\n/**/\n 2062,\n/**/\n 2061,\n/**/\n 2060,\n/**/\n 2059,\n/**/\n 2058,\n/**/\n 2057,\n/**/\n 2056,\n/**/\n 2055,\n/**/\n 2054,\n/**/\n 2053,\n/**/\n 2052,\n/**/\n 2051,\n/**/\n 2050,\n/**/\n 2049,\n/**/\n 2048,\n/**/\n 2047,\n/**/\n 2046,\n/**/\n 2045,\n/**/\n 2044,\n/**/\n 2043,\n/**/\n 2042,\n/**/\n 2041,\n/**/\n 2040,\n/**/\n 2039,\n/**/\n 2038,\n/**/\n 2037,\n/**/\n 2036,\n/**/\n 2035,\n/**/\n 2034,\n/**/\n 2033,\n/**/\n 2032,\n/**/\n 2031,\n/**/\n 2030,\n/**/\n 2029,\n/**/\n 2028,\n/**/\n 2027,\n/**/\n 2026,\n/**/\n 2025,\n/**/\n 2024,\n/**/\n 2023,\n/**/\n 2022,\n/**/\n 2021,\n/**/\n 2020,\n/**/\n 2019,\n/**/\n 2018,\n/**/\n 2017,\n/**/\n 2016,\n/**/\n 2015,\n/**/\n 2014,\n/**/\n 2013,\n/**/\n 2012,\n/**/\n 2011,\n/**/\n 2010,\n/**/\n 2009,\n/**/\n 2008,\n/**/\n 2007,\n/**/\n 2006,\n/**/\n 2005,\n/**/\n 2004,\n/**/\n 2003,\n/**/\n 2002,\n/**/\n 2001,\n/**/\n 2000,\n/**/\n 1999,\n/**/\n 1998,\n/**/\n 1997,\n/**/\n 1996,\n/**/\n 1995,\n/**/\n 1994,\n/**/\n 1993,\n/**/\n 1992,\n/**/\n 1991,\n/**/\n 1990,\n/**/\n 1989,\n/**/\n 1988,\n/**/\n 1987,\n/**/\n 1986,\n/**/\n 1985,\n/**/\n 1984,\n/**/\n 1983,\n/**/\n 1982,\n/**/\n 1981,\n/**/\n 1980,\n/**/\n 1979,\n/**/\n 1978,\n/**/\n 1977,\n/**/\n 1976,\n/**/\n 1975,\n/**/\n 1974,\n/**/\n 1973,\n/**/\n 1972,\n/**/\n 1971,\n/**/\n 1970,\n/**/\n 1969,\n/**/\n 1968,\n/**/\n 1967,\n/**/\n 1966,\n/**/\n 1965,\n/**/\n 1964,\n/**/\n 1963,\n/**/\n 1962,\n/**/\n 1961,\n/**/\n 1960,\n/**/\n 1959,\n/**/\n 1958,\n/**/\n 1957,\n/**/\n 1956,\n/**/\n 1955,\n/**/\n 1954,\n/**/\n 1953,\n/**/\n 1952,\n/**/\n 1951,\n/**/\n 1950,\n/**/\n 1949,\n/**/\n 1948,\n/**/\n 1947,\n/**/\n 1946,\n/**/\n 1945,\n/**/\n 1944,\n/**/\n 1943,\n/**/\n 1942,\n/**/\n 1941,\n/**/\n 1940,\n/**/\n 1939,\n/**/\n 1938,\n/**/\n 1937,\n/**/\n 1936,\n/**/\n 1935,\n/**/\n 1934,\n/**/\n 1933,\n/**/\n 1932,\n/**/\n 1931,\n/**/\n 1930,\n/**/\n 1929,\n/**/\n 1928,\n/**/\n 1927,\n/**/\n 1926,\n/**/\n 1925,\n/**/\n 1924,\n/**/\n 1923,\n/**/\n 1922,\n/**/\n 1921,\n/**/\n 1920,\n/**/\n 1919,\n/**/\n 1918,\n/**/\n 1917,\n/**/\n 1916,\n/**/\n 1915,\n/**/\n 1914,\n/**/\n 1913,\n/**/\n 1912,\n/**/\n 1911,\n/**/\n 1910,\n/**/\n 1909,\n/**/\n 1908,\n/**/\n 1907,\n/**/\n 1906,\n/**/\n 1905,\n/**/\n 1904,\n/**/\n 1903,\n/**/\n 1902,\n/**/\n 1901,\n/**/\n 1900,\n/**/\n 1899,\n/**/\n 1898,\n/**/\n 1897,\n/**/\n 1896,\n/**/\n 1895,\n/**/\n 1894,\n/**/\n 1893,\n/**/\n 1892,\n/**/\n 1891,\n/**/\n 1890,\n/**/\n 1889,\n/**/\n 1888,\n/**/\n 1887,\n/**/\n 1886,\n/**/\n 1885,\n/**/\n 1884,\n/**/\n 1883,\n/**/\n 1882,\n/**/\n 1881,\n/**/\n 1880,\n/**/\n 1879,\n/**/\n 1878,\n/**/\n 1877,\n/**/\n 1876,\n/**/\n 1875,\n/**/\n 1874,\n/**/\n 1873,\n/**/\n 1872,\n/**/\n 1871,\n/**/\n 1870,\n/**/\n 1869,\n/**/\n 1868,\n/**/\n 1867,\n/**/\n 1866,\n/**/\n 1865,\n/**/\n 1864,\n/**/\n 1863,\n/**/\n 1862,\n/**/\n 1861,\n/**/\n 1860,\n/**/\n 1859,\n/**/\n 1858,\n/**/\n 1857,\n/**/\n 1856,\n/**/\n 1855,\n/**/\n 1854,\n/**/\n 1853,\n/**/\n 1852,\n/**/\n 1851,\n/**/\n 1850,\n/**/\n 1849,\n/**/\n 1848,\n/**/\n 1847,\n/**/\n 1846,\n/**/\n 1845,\n/**/\n 1844,\n/**/\n 1843,\n/**/\n 1842,\n/**/\n 1841,\n/**/\n 1840,\n/**/\n 1839,\n/**/\n 1838,\n/**/\n 1837,\n/**/\n 1836,\n/**/\n 1835,\n/**/\n 1834,\n/**/\n 1833,\n/**/\n 1832,\n/**/\n 1831,\n/**/\n 1830,\n/**/\n 1829,\n/**/\n 1828,\n/**/\n 1827,\n/**/\n 1826,\n/**/\n 1825,\n/**/\n 1824,\n/**/\n 1823,\n/**/\n 1822,\n/**/\n 1821,\n/**/\n 1820,\n/**/\n 1819,\n/**/\n 1818,\n/**/\n 1817,\n/**/\n 1816,\n/**/\n 1815,\n/**/\n 1814,\n/**/\n 1813,\n/**/\n 1812,\n/**/\n 1811,\n/**/\n 1810,\n/**/\n 1809,\n/**/\n 1808,\n/**/\n 1807,\n/**/\n 1806,\n/**/\n 1805,\n/**/\n 1804,\n/**/\n 1803,\n/**/\n 1802,\n/**/\n 1801,\n/**/\n 1800,\n/**/\n 1799,\n/**/\n 1798,\n/**/\n 1797,\n/**/\n 1796,\n/**/\n 1795,\n/**/\n 1794,\n/**/\n 1793,\n/**/\n 1792,\n/**/\n 1791,\n/**/\n 1790,\n/**/\n 1789,\n/**/\n 1788,\n/**/\n 1787,\n/**/\n 1786,\n/**/\n 1785,\n/**/\n 1784,\n/**/\n 1783,\n/**/\n 1782,\n/**/\n 1781,\n/**/\n 1780,\n/**/\n 1779,\n/**/\n 1778,\n/**/\n 1777,\n/**/\n 1776,\n/**/\n 1775,\n/**/\n 1774,\n/**/\n 1773,\n/**/\n 1772,\n/**/\n 1771,\n/**/\n 1770,\n/**/\n 1769,\n/**/\n 1768,\n/**/\n 1767,\n/**/\n 1766,\n/**/\n 1765,\n/**/\n 1764,\n/**/\n 1763,\n/**/\n 1762,\n/**/\n 1761,\n/**/\n 1760,\n/**/\n 1759,\n/**/\n 1758,\n/**/\n 1757,\n/**/\n 1756,\n/**/\n 1755,\n/**/\n 1754,\n/**/\n 1753,\n/**/\n 1752,\n/**/\n 1751,\n/**/\n 1750,\n/**/\n 1749,\n/**/\n 1748,\n/**/\n 1747,\n/**/\n 1746,\n/**/\n 1745,\n/**/\n 1744,\n/**/\n 1743,\n/**/\n 1742,\n/**/\n 1741,\n/**/\n 1740,\n/**/\n 1739,\n/**/\n 1738,\n/**/\n 1737,\n/**/\n 1736,\n/**/\n 1735,\n/**/\n 1734,\n/**/\n 1733,\n/**/\n 1732,\n/**/\n 1731,\n/**/\n 1730,\n/**/\n 1729,\n/**/\n 1728,\n/**/\n 1727,\n/**/\n 1726,\n/**/\n 1725,\n/**/\n 1724,\n/**/\n 1723,\n/**/\n 1722,\n/**/\n 1721,\n/**/\n 1720,\n/**/\n 1719,\n/**/\n 1718,\n/**/\n 1717,\n/**/\n 1716,\n/**/\n 1715,\n/**/\n 1714,\n/**/\n 1713,\n/**/\n 1712,\n/**/\n 1711,\n/**/\n 1710,\n/**/\n 1709,\n/**/\n 1708,\n/**/\n 1707,\n/**/\n 1706,\n/**/\n 1705,\n/**/\n 1704,\n/**/\n 1703,\n/**/\n 1702,\n/**/\n 1701,\n/**/\n 1700,\n/**/\n 1699,\n/**/\n 1698,\n/**/\n 1697,\n/**/\n 1696,\n/**/\n 1695,\n/**/\n 1694,\n/**/\n 1693,\n/**/\n 1692,\n/**/\n 1691,\n/**/\n 1690,\n/**/\n 1689,\n/**/\n 1688,\n/**/\n 1687,\n/**/\n 1686,\n/**/\n 1685,\n/**/\n 1684,\n/**/\n 1683,\n/**/\n 1682,\n/**/\n 1681,\n/**/\n 1680,\n/**/\n 1679,\n/**/\n 1678,\n/**/\n 1677,\n/**/\n 1676,\n/**/\n 1675,\n/**/\n 1674,\n/**/\n 1673,\n/**/\n 1672,\n/**/\n 1671,\n/**/\n 1670,\n/**/\n 1669,\n/**/\n 1668,\n/**/\n 1667,\n/**/\n 1666,\n/**/\n 1665,\n/**/\n 1664,\n/**/\n 1663,\n/**/\n 1662,\n/**/\n 1661,\n/**/\n 1660,\n/**/\n 1659,\n/**/\n 1658,\n/**/\n 1657,\n/**/\n 1656,\n/**/\n 1655,\n/**/\n 1654,\n/**/\n 1653,\n/**/\n 1652,\n/**/\n 1651,\n/**/\n 1650,\n/**/\n 1649,\n/**/\n 1648,\n/**/\n 1647,\n/**/\n 1646,\n/**/\n 1645,\n/**/\n 1644,\n/**/\n 1643,\n/**/\n 1642,\n/**/\n 1641,\n/**/\n 1640,\n/**/\n 1639,\n/**/\n 1638,\n/**/\n 1637,\n/**/\n 1636,\n/**/\n 1635,\n/**/\n 1634,\n/**/\n 1633,\n/**/\n 1632,\n/**/\n 1631,\n/**/\n 1630,\n/**/\n 1629,\n/**/\n 1628,\n/**/\n 1627,\n/**/\n 1626,\n/**/\n 1625,\n/**/\n 1624,\n/**/\n 1623,\n/**/\n 1622,\n/**/\n 1621,\n/**/\n 1620,\n/**/\n 1619,\n/**/\n 1618,\n/**/\n 1617,\n/**/\n 1616,\n/**/\n 1615,\n/**/\n 1614,\n/**/\n 1613,\n/**/\n 1612,\n/**/\n 1611,\n/**/\n 1610,\n/**/\n 1609,\n/**/\n 1608,\n/**/\n 1607,\n/**/\n 1606,\n/**/\n 1605,\n/**/\n 1604,\n/**/\n 1603,\n/**/\n 1602,\n/**/\n 1601,\n/**/\n 1600,\n/**/\n 1599,\n/**/\n 1598,\n/**/\n 1597,\n/**/\n 1596,\n/**/\n 1595,\n/**/\n 1594,\n/**/\n 1593,\n/**/\n 1592,\n/**/\n 1591,\n/**/\n 1590,\n/**/\n 1589,\n/**/\n 1588,\n/**/\n 1587,\n/**/\n 1586,\n/**/\n 1585,\n/**/\n 1584,\n/**/\n 1583,\n/**/\n 1582,\n/**/\n 1581,\n/**/\n 1580,\n/**/\n 1579,\n/**/\n 1578,\n/**/\n 1577,\n/**/\n 1576,\n/**/\n 1575,\n/**/\n 1574,\n/**/\n 1573,\n/**/\n 1572,\n/**/\n 1571,\n/**/\n 1570,\n/**/\n 1569,\n/**/\n 1568,\n/**/\n 1567,\n/**/\n 1566,\n/**/\n 1565,\n/**/\n 1564,\n/**/\n 1563,\n/**/\n 1562,\n/**/\n 1561,\n/**/\n 1560,\n/**/\n 1559,\n/**/\n 1558,\n/**/\n 1557,\n/**/\n 1556,\n/**/\n 1555,\n/**/\n 1554,\n/**/\n 1553,\n/**/\n 1552,\n/**/\n 1551,\n/**/\n 1550,\n/**/\n 1549,\n/**/\n 1548,\n/**/\n 1547,\n/**/\n 1546,\n/**/\n 1545,\n/**/\n 1544,\n/**/\n 1543,\n/**/\n 1542,\n/**/\n 1541,\n/**/\n 1540,\n/**/\n 1539,\n/**/\n 1538,\n/**/\n 1537,\n/**/\n 1536,\n/**/\n 1535,\n/**/\n 1534,\n/**/\n 1533,\n/**/\n 1532,\n/**/\n 1531,\n/**/\n 1530,\n/**/\n 1529,\n/**/\n 1528,\n/**/\n 1527,\n/**/\n 1526,\n/**/\n 1525,\n/**/\n 1524,\n/**/\n 1523,\n/**/\n 1522,\n/**/\n 1521,\n/**/\n 1520,\n/**/\n 1519,\n/**/\n 1518,\n/**/\n 1517,\n/**/\n 1516,\n/**/\n 1515,\n/**/\n 1514,\n/**/\n 1513,\n/**/\n 1512,\n/**/\n 1511,\n/**/\n 1510,\n/**/\n 1509,\n/**/\n 1508,\n/**/\n 1507,\n/**/\n 1506,\n/**/\n 1505,\n/**/\n 1504,\n/**/\n 1503,\n/**/\n 1502,\n/**/\n 1501,\n/**/\n 1500,\n/**/\n 1499,\n/**/\n 1498,\n/**/\n 1497,\n/**/\n 1496,\n/**/\n 1495,\n/**/\n 1494,\n/**/\n 1493,\n/**/\n 1492,\n/**/\n 1491,\n/**/\n 1490,\n/**/\n 1489,\n/**/\n 1488,\n/**/\n 1487,\n/**/\n 1486,\n/**/\n 1485,\n/**/\n 1484,\n/**/\n 1483,\n/**/\n 1482,\n/**/\n 1481,\n/**/\n 1480,\n/**/\n 1479,\n/**/\n 1478,\n/**/\n 1477,\n/**/\n 1476,\n/**/\n 1475,\n/**/\n 1474,\n/**/\n 1473,\n/**/\n 1472,\n/**/\n 1471,\n/**/\n 1470,\n/**/\n 1469,\n/**/\n 1468,\n/**/\n 1467,\n/**/\n 1466,\n/**/\n 1465,\n/**/\n 1464,\n/**/\n 1463,\n/**/\n 1462,\n/**/\n 1461,\n/**/\n 1460,\n/**/\n 1459,\n/**/\n 1458,\n/**/\n 1457,\n/**/\n 1456,\n/**/\n 1455,\n/**/\n 1454,\n/**/\n 1453,\n/**/\n 1452,\n/**/\n 1451,\n/**/\n 1450,\n/**/\n 1449,\n/**/\n 1448,\n/**/\n 1447,\n/**/\n 1446,\n/**/\n 1445,\n/**/\n 1444,\n/**/\n 1443,\n/**/\n 1442,\n/**/\n 1441,\n/**/\n 1440,\n/**/\n 1439,\n/**/\n 1438,\n/**/\n 1437,\n/**/\n 1436,\n/**/\n 1435,\n/**/\n 1434,\n/**/\n 1433,\n/**/\n 1432,\n/**/\n 1431,\n/**/\n 1430,\n/**/\n 1429,\n/**/\n 1428,\n/**/\n 1427,\n/**/\n 1426,\n/**/\n 1425,\n/**/\n 1424,\n/**/\n 1423,\n/**/\n 1422,\n/**/\n 1421,\n/**/\n 1420,\n/**/\n 1419,\n/**/\n 1418,\n/**/\n 1417,\n/**/\n 1416,\n/**/\n 1415,\n/**/\n 1414,\n/**/\n 1413,\n/**/\n 1412,\n/**/\n 1411,\n/**/\n 1410,\n/**/\n 1409,\n/**/\n 1408,\n/**/\n 1407,\n/**/\n 1406,\n/**/\n 1405,\n/**/\n 1404,\n/**/\n 1403,\n/**/\n 1402,\n/**/\n 1401,\n/**/\n 1400,\n/**/\n 1399,\n/**/\n 1398,\n/**/\n 1397,\n/**/\n 1396,\n/**/\n 1395,\n/**/\n 1394,\n/**/\n 1393,\n/**/\n 1392,\n/**/\n 1391,\n/**/\n 1390,\n/**/\n 1389,\n/**/\n 1388,\n/**/\n 1387,\n/**/\n 1386,\n/**/\n 1385,\n/**/\n 1384,\n/**/\n 1383,\n/**/\n 1382,\n/**/\n 1381,\n/**/\n 1380,\n/**/\n 1379,\n/**/\n 1378,\n/**/\n 1377,\n/**/\n 1376,\n/**/\n 1375,\n/**/\n 1374,\n/**/\n 1373,\n/**/\n 1372,\n/**/\n 1371,\n/**/\n 1370,\n/**/\n 1369,\n/**/\n 1368,\n/**/\n 1367,\n/**/\n 1366,\n/**/\n 1365,\n/**/\n 1364,\n/**/\n 1363,\n/**/\n 1362,\n/**/\n 1361,\n/**/\n 1360,\n/**/\n 1359,\n/**/\n 1358,\n/**/\n 1357,\n/**/\n 1356,\n/**/\n 1355,\n/**/\n 1354,\n/**/\n 1353,\n/**/\n 1352,\n/**/\n 1351,\n/**/\n 1350,\n/**/\n 1349,\n/**/\n 1348,\n/**/\n 1347,\n/**/\n 1346,\n/**/\n 1345,\n/**/\n 1344,\n/**/\n 1343,\n/**/\n 1342,\n/**/\n 1341,\n/**/\n 1340,\n/**/\n 1339,\n/**/\n 1338,\n/**/\n 1337,\n/**/\n 1336,\n/**/\n 1335,\n/**/\n 1334,\n/**/\n 1333,\n/**/\n 1332,\n/**/\n 1331,\n/**/\n 1330,\n/**/\n 1329,\n/**/\n 1328,\n/**/\n 1327,\n/**/\n 1326,\n/**/\n 1325,\n/**/\n 1324,\n/**/\n 1323,\n/**/\n 1322,\n/**/\n 1321,\n/**/\n 1320,\n/**/\n 1319,\n/**/\n 1318,\n/**/\n 1317,\n/**/\n 1316,\n/**/\n 1315,\n/**/\n 1314,\n/**/\n 1313,\n/**/\n 1312,\n/**/\n 1311,\n/**/\n 1310,\n/**/\n 1309,\n/**/\n 1308,\n/**/\n 1307,\n/**/\n 1306,\n/**/\n 1305,\n/**/\n 1304,\n/**/\n 1303,\n/**/\n 1302,\n/**/\n 1301,\n/**/\n 1300,\n/**/\n 1299,\n/**/\n 1298,\n/**/\n 1297,\n/**/\n 1296,\n/**/\n 1295,\n/**/\n 1294,\n/**/\n 1293,\n/**/\n 1292,\n/**/\n 1291,\n/**/\n 1290,\n/**/\n 1289,\n/**/\n 1288,\n/**/\n 1287,\n/**/\n 1286,\n/**/\n 1285,\n/**/\n 1284,\n/**/\n 1283,\n/**/\n 1282,\n/**/\n 1281,\n/**/\n 1280,\n/**/\n 1279,\n/**/\n 1278,\n/**/\n 1277,\n/**/\n 1276,\n/**/\n 1275,\n/**/\n 1274,\n/**/\n 1273,\n/**/\n 1272,\n/**/\n 1271,\n/**/\n 1270,\n/**/\n 1269,\n/**/\n 1268,\n/**/\n 1267,\n/**/\n 1266,\n/**/\n 1265,\n/**/\n 1264,\n/**/\n 1263,\n/**/\n 1262,\n/**/\n 1261,\n/**/\n 1260,\n/**/\n 1259,\n/**/\n 1258,\n/**/\n 1257,\n/**/\n 1256,\n/**/\n 1255,\n/**/\n 1254,\n/**/\n 1253,\n/**/\n 1252,\n/**/\n 1251,\n/**/\n 1250,\n/**/\n 1249,\n/**/\n 1248,\n/**/\n 1247,\n/**/\n 1246,\n/**/\n 1245,\n/**/\n 1244,\n/**/\n 1243,\n/**/\n 1242,\n/**/\n 1241,\n/**/\n 1240,\n/**/\n 1239,\n/**/\n 1238,\n/**/\n 1237,\n/**/\n 1236,\n/**/\n 1235,\n/**/\n 1234,\n/**/\n 1233,\n/**/\n 1232,\n/**/\n 1231,\n/**/\n 1230,\n/**/\n 1229,\n/**/\n 1228,\n/**/\n 1227,\n/**/\n 1226,\n/**/\n 1225,\n/**/\n 1224,\n/**/\n 1223,\n/**/\n 1222,\n/**/\n 1221,\n/**/\n 1220,\n/**/\n 1219,\n/**/\n 1218,\n/**/\n 1217,\n/**/\n 1216,\n/**/\n 1215,\n/**/\n 1214,\n/**/\n 1213,\n/**/\n 1212,\n/**/\n 1211,\n/**/\n 1210,\n/**/\n 1209,\n/**/\n 1208,\n/**/\n 1207,\n/**/\n 1206,\n/**/\n 1205,\n/**/\n 1204,\n/**/\n 1203,\n/**/\n 1202,\n/**/\n 1201,\n/**/\n 1200,\n/**/\n 1199,\n/**/\n 1198,\n/**/\n 1197,\n/**/\n 1196,\n/**/\n 1195,\n/**/\n 1194,\n/**/\n 1193,\n/**/\n 1192,\n/**/\n 1191,\n/**/\n 1190,\n/**/\n 1189,\n/**/\n 1188,\n/**/\n 1187,\n/**/\n 1186,\n/**/\n 1185,\n/**/\n 1184,\n/**/\n 1183,\n/**/\n 1182,\n/**/\n 1181,\n/**/\n 1180,\n/**/\n 1179,\n/**/\n 1178,\n/**/\n 1177,\n/**/\n 1176,\n/**/\n 1175,\n/**/\n 1174,\n/**/\n 1173,\n/**/\n 1172,\n/**/\n 1171,\n/**/\n 1170,\n/**/\n 1169,\n/**/\n 1168,\n/**/\n 1167,\n/**/\n 1166,\n/**/\n 1165,\n/**/\n 1164,\n/**/\n 1163,\n/**/\n 1162,\n/**/\n 1161,\n/**/\n 1160,\n/**/\n 1159,\n/**/\n 1158,\n/**/\n 1157,\n/**/\n 1156,\n/**/\n 1155,\n/**/\n 1154,\n/**/\n 1153,\n/**/\n 1152,\n/**/\n 1151,\n/**/\n 1150,\n/**/\n 1149,\n/**/\n 1148,\n/**/\n 1147,\n/**/\n 1146,\n/**/\n 1145,\n/**/\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 while (l < h)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\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 version8<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": [1491, 804, 736], "buggy_code_start_loc": [1278, 804, 736], "filenames": ["src/spell.c", "src/testdir/test_spell_utf8.vim", "src/version.c"], "fixing_code_end_loc": [1495, 820, 739], "fixing_code_start_loc": [1278, 805, 737], "message": "Use After Free in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B6CDC65-37D1-4A6A-B6C5-7B58DC5757ED", "versionEndExcluding": "8.2.5072", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "0146DEE5-EF72-48C3-9DDD-28EA3595BDD1", "versionEndExcluding": "11.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7B7BC361-3A04-4C88-A3AE-82B9993A73A0", "versionEndExcluding": "12.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use After Free in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Un Uso de Memoria Previamente Liberada en el repositorio GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2042", "lastModified": "2023-05-03T12:15:40.820", "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": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 0.8, "impactScore": 6.0, "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-06-10T19:15:08.813", "references": [{"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/28"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/41"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/43"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/45"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/8628b4cd-4055-4059-aed4-64f7fdc10eba"}, {"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"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213443"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213444"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213488"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, "type": "CWE-416"}
| 317
|
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 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 5072,",
"/**/\n 5071,\n/**/\n 5070,\n/**/\n 5069,\n/**/\n 5068,\n/**/\n 5067,\n/**/\n 5066,\n/**/\n 5065,\n/**/\n 5064,\n/**/\n 5063,\n/**/\n 5062,\n/**/\n 5061,\n/**/\n 5060,\n/**/\n 5059,\n/**/\n 5058,\n/**/\n 5057,\n/**/\n 5056,\n/**/\n 5055,\n/**/\n 5054,\n/**/\n 5053,\n/**/\n 5052,\n/**/\n 5051,\n/**/\n 5050,\n/**/\n 5049,\n/**/\n 5048,\n/**/\n 5047,\n/**/\n 5046,\n/**/\n 5045,\n/**/\n 5044,\n/**/\n 5043,\n/**/\n 5042,\n/**/\n 5041,\n/**/\n 5040,\n/**/\n 5039,\n/**/\n 5038,\n/**/\n 5037,\n/**/\n 5036,\n/**/\n 5035,\n/**/\n 5034,\n/**/\n 5033,\n/**/\n 5032,\n/**/\n 5031,\n/**/\n 5030,\n/**/\n 5029,\n/**/\n 5028,\n/**/\n 5027,\n/**/\n 5026,\n/**/\n 5025,\n/**/\n 5024,\n/**/\n 5023,\n/**/\n 5022,\n/**/\n 5021,\n/**/\n 5020,\n/**/\n 5019,\n/**/\n 5018,\n/**/\n 5017,\n/**/\n 5016,\n/**/\n 5015,\n/**/\n 5014,\n/**/\n 5013,\n/**/\n 5012,\n/**/\n 5011,\n/**/\n 5010,\n/**/\n 5009,\n/**/\n 5008,\n/**/\n 5007,\n/**/\n 5006,\n/**/\n 5005,\n/**/\n 5004,\n/**/\n 5003,\n/**/\n 5002,\n/**/\n 5001,\n/**/\n 5000,\n/**/\n 4999,\n/**/\n 4998,\n/**/\n 4997,\n/**/\n 4996,\n/**/\n 4995,\n/**/\n 4994,\n/**/\n 4993,\n/**/\n 4992,\n/**/\n 4991,\n/**/\n 4990,\n/**/\n 4989,\n/**/\n 4988,\n/**/\n 4987,\n/**/\n 4986,\n/**/\n 4985,\n/**/\n 4984,\n/**/\n 4983,\n/**/\n 4982,\n/**/\n 4981,\n/**/\n 4980,\n/**/\n 4979,\n/**/\n 4978,\n/**/\n 4977,\n/**/\n 4976,\n/**/\n 4975,\n/**/\n 4974,\n/**/\n 4973,\n/**/\n 4972,\n/**/\n 4971,\n/**/\n 4970,\n/**/\n 4969,\n/**/\n 4968,\n/**/\n 4967,\n/**/\n 4966,\n/**/\n 4965,\n/**/\n 4964,\n/**/\n 4963,\n/**/\n 4962,\n/**/\n 4961,\n/**/\n 4960,\n/**/\n 4959,\n/**/\n 4958,\n/**/\n 4957,\n/**/\n 4956,\n/**/\n 4955,\n/**/\n 4954,\n/**/\n 4953,\n/**/\n 4952,\n/**/\n 4951,\n/**/\n 4950,\n/**/\n 4949,\n/**/\n 4948,\n/**/\n 4947,\n/**/\n 4946,\n/**/\n 4945,\n/**/\n 4944,\n/**/\n 4943,\n/**/\n 4942,\n/**/\n 4941,\n/**/\n 4940,\n/**/\n 4939,\n/**/\n 4938,\n/**/\n 4937,\n/**/\n 4936,\n/**/\n 4935,\n/**/\n 4934,\n/**/\n 4933,\n/**/\n 4932,\n/**/\n 4931,\n/**/\n 4930,\n/**/\n 4929,\n/**/\n 4928,\n/**/\n 4927,\n/**/\n 4926,\n/**/\n 4925,\n/**/\n 4924,\n/**/\n 4923,\n/**/\n 4922,\n/**/\n 4921,\n/**/\n 4920,\n/**/\n 4919,\n/**/\n 4918,\n/**/\n 4917,\n/**/\n 4916,\n/**/\n 4915,\n/**/\n 4914,\n/**/\n 4913,\n/**/\n 4912,\n/**/\n 4911,\n/**/\n 4910,\n/**/\n 4909,\n/**/\n 4908,\n/**/\n 4907,\n/**/\n 4906,\n/**/\n 4905,\n/**/\n 4904,\n/**/\n 4903,\n/**/\n 4902,\n/**/\n 4901,\n/**/\n 4900,\n/**/\n 4899,\n/**/\n 4898,\n/**/\n 4897,\n/**/\n 4896,\n/**/\n 4895,\n/**/\n 4894,\n/**/\n 4893,\n/**/\n 4892,\n/**/\n 4891,\n/**/\n 4890,\n/**/\n 4889,\n/**/\n 4888,\n/**/\n 4887,\n/**/\n 4886,\n/**/\n 4885,\n/**/\n 4884,\n/**/\n 4883,\n/**/\n 4882,\n/**/\n 4881,\n/**/\n 4880,\n/**/\n 4879,\n/**/\n 4878,\n/**/\n 4877,\n/**/\n 4876,\n/**/\n 4875,\n/**/\n 4874,\n/**/\n 4873,\n/**/\n 4872,\n/**/\n 4871,\n/**/\n 4870,\n/**/\n 4869,\n/**/\n 4868,\n/**/\n 4867,\n/**/\n 4866,\n/**/\n 4865,\n/**/\n 4864,\n/**/\n 4863,\n/**/\n 4862,\n/**/\n 4861,\n/**/\n 4860,\n/**/\n 4859,\n/**/\n 4858,\n/**/\n 4857,\n/**/\n 4856,\n/**/\n 4855,\n/**/\n 4854,\n/**/\n 4853,\n/**/\n 4852,\n/**/\n 4851,\n/**/\n 4850,\n/**/\n 4849,\n/**/\n 4848,\n/**/\n 4847,\n/**/\n 4846,\n/**/\n 4845,\n/**/\n 4844,\n/**/\n 4843,\n/**/\n 4842,\n/**/\n 4841,\n/**/\n 4840,\n/**/\n 4839,\n/**/\n 4838,\n/**/\n 4837,\n/**/\n 4836,\n/**/\n 4835,\n/**/\n 4834,\n/**/\n 4833,\n/**/\n 4832,\n/**/\n 4831,\n/**/\n 4830,\n/**/\n 4829,\n/**/\n 4828,\n/**/\n 4827,\n/**/\n 4826,\n/**/\n 4825,\n/**/\n 4824,\n/**/\n 4823,\n/**/\n 4822,\n/**/\n 4821,\n/**/\n 4820,\n/**/\n 4819,\n/**/\n 4818,\n/**/\n 4817,\n/**/\n 4816,\n/**/\n 4815,\n/**/\n 4814,\n/**/\n 4813,\n/**/\n 4812,\n/**/\n 4811,\n/**/\n 4810,\n/**/\n 4809,\n/**/\n 4808,\n/**/\n 4807,\n/**/\n 4806,\n/**/\n 4805,\n/**/\n 4804,\n/**/\n 4803,\n/**/\n 4802,\n/**/\n 4801,\n/**/\n 4800,\n/**/\n 4799,\n/**/\n 4798,\n/**/\n 4797,\n/**/\n 4796,\n/**/\n 4795,\n/**/\n 4794,\n/**/\n 4793,\n/**/\n 4792,\n/**/\n 4791,\n/**/\n 4790,\n/**/\n 4789,\n/**/\n 4788,\n/**/\n 4787,\n/**/\n 4786,\n/**/\n 4785,\n/**/\n 4784,\n/**/\n 4783,\n/**/\n 4782,\n/**/\n 4781,\n/**/\n 4780,\n/**/\n 4779,\n/**/\n 4778,\n/**/\n 4777,\n/**/\n 4776,\n/**/\n 4775,\n/**/\n 4774,\n/**/\n 4773,\n/**/\n 4772,\n/**/\n 4771,\n/**/\n 4770,\n/**/\n 4769,\n/**/\n 4768,\n/**/\n 4767,\n/**/\n 4766,\n/**/\n 4765,\n/**/\n 4764,\n/**/\n 4763,\n/**/\n 4762,\n/**/\n 4761,\n/**/\n 4760,\n/**/\n 4759,\n/**/\n 4758,\n/**/\n 4757,\n/**/\n 4756,\n/**/\n 4755,\n/**/\n 4754,\n/**/\n 4753,\n/**/\n 4752,\n/**/\n 4751,\n/**/\n 4750,\n/**/\n 4749,\n/**/\n 4748,\n/**/\n 4747,\n/**/\n 4746,\n/**/\n 4745,\n/**/\n 4744,\n/**/\n 4743,\n/**/\n 4742,\n/**/\n 4741,\n/**/\n 4740,\n/**/\n 4739,\n/**/\n 4738,\n/**/\n 4737,\n/**/\n 4736,\n/**/\n 4735,\n/**/\n 4734,\n/**/\n 4733,\n/**/\n 4732,\n/**/\n 4731,\n/**/\n 4730,\n/**/\n 4729,\n/**/\n 4728,\n/**/\n 4727,\n/**/\n 4726,\n/**/\n 4725,\n/**/\n 4724,\n/**/\n 4723,\n/**/\n 4722,\n/**/\n 4721,\n/**/\n 4720,\n/**/\n 4719,\n/**/\n 4718,\n/**/\n 4717,\n/**/\n 4716,\n/**/\n 4715,\n/**/\n 4714,\n/**/\n 4713,\n/**/\n 4712,\n/**/\n 4711,\n/**/\n 4710,\n/**/\n 4709,\n/**/\n 4708,\n/**/\n 4707,\n/**/\n 4706,\n/**/\n 4705,\n/**/\n 4704,\n/**/\n 4703,\n/**/\n 4702,\n/**/\n 4701,\n/**/\n 4700,\n/**/\n 4699,\n/**/\n 4698,\n/**/\n 4697,\n/**/\n 4696,\n/**/\n 4695,\n/**/\n 4694,\n/**/\n 4693,\n/**/\n 4692,\n/**/\n 4691,\n/**/\n 4690,\n/**/\n 4689,\n/**/\n 4688,\n/**/\n 4687,\n/**/\n 4686,\n/**/\n 4685,\n/**/\n 4684,\n/**/\n 4683,\n/**/\n 4682,\n/**/\n 4681,\n/**/\n 4680,\n/**/\n 4679,\n/**/\n 4678,\n/**/\n 4677,\n/**/\n 4676,\n/**/\n 4675,\n/**/\n 4674,\n/**/\n 4673,\n/**/\n 4672,\n/**/\n 4671,\n/**/\n 4670,\n/**/\n 4669,\n/**/\n 4668,\n/**/\n 4667,\n/**/\n 4666,\n/**/\n 4665,\n/**/\n 4664,\n/**/\n 4663,\n/**/\n 4662,\n/**/\n 4661,\n/**/\n 4660,\n/**/\n 4659,\n/**/\n 4658,\n/**/\n 4657,\n/**/\n 4656,\n/**/\n 4655,\n/**/\n 4654,\n/**/\n 4653,\n/**/\n 4652,\n/**/\n 4651,\n/**/\n 4650,\n/**/\n 4649,\n/**/\n 4648,\n/**/\n 4647,\n/**/\n 4646,\n/**/\n 4645,\n/**/\n 4644,\n/**/\n 4643,\n/**/\n 4642,\n/**/\n 4641,\n/**/\n 4640,\n/**/\n 4639,\n/**/\n 4638,\n/**/\n 4637,\n/**/\n 4636,\n/**/\n 4635,\n/**/\n 4634,\n/**/\n 4633,\n/**/\n 4632,\n/**/\n 4631,\n/**/\n 4630,\n/**/\n 4629,\n/**/\n 4628,\n/**/\n 4627,\n/**/\n 4626,\n/**/\n 4625,\n/**/\n 4624,\n/**/\n 4623,\n/**/\n 4622,\n/**/\n 4621,\n/**/\n 4620,\n/**/\n 4619,\n/**/\n 4618,\n/**/\n 4617,\n/**/\n 4616,\n/**/\n 4615,\n/**/\n 4614,\n/**/\n 4613,\n/**/\n 4612,\n/**/\n 4611,\n/**/\n 4610,\n/**/\n 4609,\n/**/\n 4608,\n/**/\n 4607,\n/**/\n 4606,\n/**/\n 4605,\n/**/\n 4604,\n/**/\n 4603,\n/**/\n 4602,\n/**/\n 4601,\n/**/\n 4600,\n/**/\n 4599,\n/**/\n 4598,\n/**/\n 4597,\n/**/\n 4596,\n/**/\n 4595,\n/**/\n 4594,\n/**/\n 4593,\n/**/\n 4592,\n/**/\n 4591,\n/**/\n 4590,\n/**/\n 4589,\n/**/\n 4588,\n/**/\n 4587,\n/**/\n 4586,\n/**/\n 4585,\n/**/\n 4584,\n/**/\n 4583,\n/**/\n 4582,\n/**/\n 4581,\n/**/\n 4580,\n/**/\n 4579,\n/**/\n 4578,\n/**/\n 4577,\n/**/\n 4576,\n/**/\n 4575,\n/**/\n 4574,\n/**/\n 4573,\n/**/\n 4572,\n/**/\n 4571,\n/**/\n 4570,\n/**/\n 4569,\n/**/\n 4568,\n/**/\n 4567,\n/**/\n 4566,\n/**/\n 4565,\n/**/\n 4564,\n/**/\n 4563,\n/**/\n 4562,\n/**/\n 4561,\n/**/\n 4560,\n/**/\n 4559,\n/**/\n 4558,\n/**/\n 4557,\n/**/\n 4556,\n/**/\n 4555,\n/**/\n 4554,\n/**/\n 4553,\n/**/\n 4552,\n/**/\n 4551,\n/**/\n 4550,\n/**/\n 4549,\n/**/\n 4548,\n/**/\n 4547,\n/**/\n 4546,\n/**/\n 4545,\n/**/\n 4544,\n/**/\n 4543,\n/**/\n 4542,\n/**/\n 4541,\n/**/\n 4540,\n/**/\n 4539,\n/**/\n 4538,\n/**/\n 4537,\n/**/\n 4536,\n/**/\n 4535,\n/**/\n 4534,\n/**/\n 4533,\n/**/\n 4532,\n/**/\n 4531,\n/**/\n 4530,\n/**/\n 4529,\n/**/\n 4528,\n/**/\n 4527,\n/**/\n 4526,\n/**/\n 4525,\n/**/\n 4524,\n/**/\n 4523,\n/**/\n 4522,\n/**/\n 4521,\n/**/\n 4520,\n/**/\n 4519,\n/**/\n 4518,\n/**/\n 4517,\n/**/\n 4516,\n/**/\n 4515,\n/**/\n 4514,\n/**/\n 4513,\n/**/\n 4512,\n/**/\n 4511,\n/**/\n 4510,\n/**/\n 4509,\n/**/\n 4508,\n/**/\n 4507,\n/**/\n 4506,\n/**/\n 4505,\n/**/\n 4504,\n/**/\n 4503,\n/**/\n 4502,\n/**/\n 4501,\n/**/\n 4500,\n/**/\n 4499,\n/**/\n 4498,\n/**/\n 4497,\n/**/\n 4496,\n/**/\n 4495,\n/**/\n 4494,\n/**/\n 4493,\n/**/\n 4492,\n/**/\n 4491,\n/**/\n 4490,\n/**/\n 4489,\n/**/\n 4488,\n/**/\n 4487,\n/**/\n 4486,\n/**/\n 4485,\n/**/\n 4484,\n/**/\n 4483,\n/**/\n 4482,\n/**/\n 4481,\n/**/\n 4480,\n/**/\n 4479,\n/**/\n 4478,\n/**/\n 4477,\n/**/\n 4476,\n/**/\n 4475,\n/**/\n 4474,\n/**/\n 4473,\n/**/\n 4472,\n/**/\n 4471,\n/**/\n 4470,\n/**/\n 4469,\n/**/\n 4468,\n/**/\n 4467,\n/**/\n 4466,\n/**/\n 4465,\n/**/\n 4464,\n/**/\n 4463,\n/**/\n 4462,\n/**/\n 4461,\n/**/\n 4460,\n/**/\n 4459,\n/**/\n 4458,\n/**/\n 4457,\n/**/\n 4456,\n/**/\n 4455,\n/**/\n 4454,\n/**/\n 4453,\n/**/\n 4452,\n/**/\n 4451,\n/**/\n 4450,\n/**/\n 4449,\n/**/\n 4448,\n/**/\n 4447,\n/**/\n 4446,\n/**/\n 4445,\n/**/\n 4444,\n/**/\n 4443,\n/**/\n 4442,\n/**/\n 4441,\n/**/\n 4440,\n/**/\n 4439,\n/**/\n 4438,\n/**/\n 4437,\n/**/\n 4436,\n/**/\n 4435,\n/**/\n 4434,\n/**/\n 4433,\n/**/\n 4432,\n/**/\n 4431,\n/**/\n 4430,\n/**/\n 4429,\n/**/\n 4428,\n/**/\n 4427,\n/**/\n 4426,\n/**/\n 4425,\n/**/\n 4424,\n/**/\n 4423,\n/**/\n 4422,\n/**/\n 4421,\n/**/\n 4420,\n/**/\n 4419,\n/**/\n 4418,\n/**/\n 4417,\n/**/\n 4416,\n/**/\n 4415,\n/**/\n 4414,\n/**/\n 4413,\n/**/\n 4412,\n/**/\n 4411,\n/**/\n 4410,\n/**/\n 4409,\n/**/\n 4408,\n/**/\n 4407,\n/**/\n 4406,\n/**/\n 4405,\n/**/\n 4404,\n/**/\n 4403,\n/**/\n 4402,\n/**/\n 4401,\n/**/\n 4400,\n/**/\n 4399,\n/**/\n 4398,\n/**/\n 4397,\n/**/\n 4396,\n/**/\n 4395,\n/**/\n 4394,\n/**/\n 4393,\n/**/\n 4392,\n/**/\n 4391,\n/**/\n 4390,\n/**/\n 4389,\n/**/\n 4388,\n/**/\n 4387,\n/**/\n 4386,\n/**/\n 4385,\n/**/\n 4384,\n/**/\n 4383,\n/**/\n 4382,\n/**/\n 4381,\n/**/\n 4380,\n/**/\n 4379,\n/**/\n 4378,\n/**/\n 4377,\n/**/\n 4376,\n/**/\n 4375,\n/**/\n 4374,\n/**/\n 4373,\n/**/\n 4372,\n/**/\n 4371,\n/**/\n 4370,\n/**/\n 4369,\n/**/\n 4368,\n/**/\n 4367,\n/**/\n 4366,\n/**/\n 4365,\n/**/\n 4364,\n/**/\n 4363,\n/**/\n 4362,\n/**/\n 4361,\n/**/\n 4360,\n/**/\n 4359,\n/**/\n 4358,\n/**/\n 4357,\n/**/\n 4356,\n/**/\n 4355,\n/**/\n 4354,\n/**/\n 4353,\n/**/\n 4352,\n/**/\n 4351,\n/**/\n 4350,\n/**/\n 4349,\n/**/\n 4348,\n/**/\n 4347,\n/**/\n 4346,\n/**/\n 4345,\n/**/\n 4344,\n/**/\n 4343,\n/**/\n 4342,\n/**/\n 4341,\n/**/\n 4340,\n/**/\n 4339,\n/**/\n 4338,\n/**/\n 4337,\n/**/\n 4336,\n/**/\n 4335,\n/**/\n 4334,\n/**/\n 4333,\n/**/\n 4332,\n/**/\n 4331,\n/**/\n 4330,\n/**/\n 4329,\n/**/\n 4328,\n/**/\n 4327,\n/**/\n 4326,\n/**/\n 4325,\n/**/\n 4324,\n/**/\n 4323,\n/**/\n 4322,\n/**/\n 4321,\n/**/\n 4320,\n/**/\n 4319,\n/**/\n 4318,\n/**/\n 4317,\n/**/\n 4316,\n/**/\n 4315,\n/**/\n 4314,\n/**/\n 4313,\n/**/\n 4312,\n/**/\n 4311,\n/**/\n 4310,\n/**/\n 4309,\n/**/\n 4308,\n/**/\n 4307,\n/**/\n 4306,\n/**/\n 4305,\n/**/\n 4304,\n/**/\n 4303,\n/**/\n 4302,\n/**/\n 4301,\n/**/\n 4300,\n/**/\n 4299,\n/**/\n 4298,\n/**/\n 4297,\n/**/\n 4296,\n/**/\n 4295,\n/**/\n 4294,\n/**/\n 4293,\n/**/\n 4292,\n/**/\n 4291,\n/**/\n 4290,\n/**/\n 4289,\n/**/\n 4288,\n/**/\n 4287,\n/**/\n 4286,\n/**/\n 4285,\n/**/\n 4284,\n/**/\n 4283,\n/**/\n 4282,\n/**/\n 4281,\n/**/\n 4280,\n/**/\n 4279,\n/**/\n 4278,\n/**/\n 4277,\n/**/\n 4276,\n/**/\n 4275,\n/**/\n 4274,\n/**/\n 4273,\n/**/\n 4272,\n/**/\n 4271,\n/**/\n 4270,\n/**/\n 4269,\n/**/\n 4268,\n/**/\n 4267,\n/**/\n 4266,\n/**/\n 4265,\n/**/\n 4264,\n/**/\n 4263,\n/**/\n 4262,\n/**/\n 4261,\n/**/\n 4260,\n/**/\n 4259,\n/**/\n 4258,\n/**/\n 4257,\n/**/\n 4256,\n/**/\n 4255,\n/**/\n 4254,\n/**/\n 4253,\n/**/\n 4252,\n/**/\n 4251,\n/**/\n 4250,\n/**/\n 4249,\n/**/\n 4248,\n/**/\n 4247,\n/**/\n 4246,\n/**/\n 4245,\n/**/\n 4244,\n/**/\n 4243,\n/**/\n 4242,\n/**/\n 4241,\n/**/\n 4240,\n/**/\n 4239,\n/**/\n 4238,\n/**/\n 4237,\n/**/\n 4236,\n/**/\n 4235,\n/**/\n 4234,\n/**/\n 4233,\n/**/\n 4232,\n/**/\n 4231,\n/**/\n 4230,\n/**/\n 4229,\n/**/\n 4228,\n/**/\n 4227,\n/**/\n 4226,\n/**/\n 4225,\n/**/\n 4224,\n/**/\n 4223,\n/**/\n 4222,\n/**/\n 4221,\n/**/\n 4220,\n/**/\n 4219,\n/**/\n 4218,\n/**/\n 4217,\n/**/\n 4216,\n/**/\n 4215,\n/**/\n 4214,\n/**/\n 4213,\n/**/\n 4212,\n/**/\n 4211,\n/**/\n 4210,\n/**/\n 4209,\n/**/\n 4208,\n/**/\n 4207,\n/**/\n 4206,\n/**/\n 4205,\n/**/\n 4204,\n/**/\n 4203,\n/**/\n 4202,\n/**/\n 4201,\n/**/\n 4200,\n/**/\n 4199,\n/**/\n 4198,\n/**/\n 4197,\n/**/\n 4196,\n/**/\n 4195,\n/**/\n 4194,\n/**/\n 4193,\n/**/\n 4192,\n/**/\n 4191,\n/**/\n 4190,\n/**/\n 4189,\n/**/\n 4188,\n/**/\n 4187,\n/**/\n 4186,\n/**/\n 4185,\n/**/\n 4184,\n/**/\n 4183,\n/**/\n 4182,\n/**/\n 4181,\n/**/\n 4180,\n/**/\n 4179,\n/**/\n 4178,\n/**/\n 4177,\n/**/\n 4176,\n/**/\n 4175,\n/**/\n 4174,\n/**/\n 4173,\n/**/\n 4172,\n/**/\n 4171,\n/**/\n 4170,\n/**/\n 4169,\n/**/\n 4168,\n/**/\n 4167,\n/**/\n 4166,\n/**/\n 4165,\n/**/\n 4164,\n/**/\n 4163,\n/**/\n 4162,\n/**/\n 4161,\n/**/\n 4160,\n/**/\n 4159,\n/**/\n 4158,\n/**/\n 4157,\n/**/\n 4156,\n/**/\n 4155,\n/**/\n 4154,\n/**/\n 4153,\n/**/\n 4152,\n/**/\n 4151,\n/**/\n 4150,\n/**/\n 4149,\n/**/\n 4148,\n/**/\n 4147,\n/**/\n 4146,\n/**/\n 4145,\n/**/\n 4144,\n/**/\n 4143,\n/**/\n 4142,\n/**/\n 4141,\n/**/\n 4140,\n/**/\n 4139,\n/**/\n 4138,\n/**/\n 4137,\n/**/\n 4136,\n/**/\n 4135,\n/**/\n 4134,\n/**/\n 4133,\n/**/\n 4132,\n/**/\n 4131,\n/**/\n 4130,\n/**/\n 4129,\n/**/\n 4128,\n/**/\n 4127,\n/**/\n 4126,\n/**/\n 4125,\n/**/\n 4124,\n/**/\n 4123,\n/**/\n 4122,\n/**/\n 4121,\n/**/\n 4120,\n/**/\n 4119,\n/**/\n 4118,\n/**/\n 4117,\n/**/\n 4116,\n/**/\n 4115,\n/**/\n 4114,\n/**/\n 4113,\n/**/\n 4112,\n/**/\n 4111,\n/**/\n 4110,\n/**/\n 4109,\n/**/\n 4108,\n/**/\n 4107,\n/**/\n 4106,\n/**/\n 4105,\n/**/\n 4104,\n/**/\n 4103,\n/**/\n 4102,\n/**/\n 4101,\n/**/\n 4100,\n/**/\n 4099,\n/**/\n 4098,\n/**/\n 4097,\n/**/\n 4096,\n/**/\n 4095,\n/**/\n 4094,\n/**/\n 4093,\n/**/\n 4092,\n/**/\n 4091,\n/**/\n 4090,\n/**/\n 4089,\n/**/\n 4088,\n/**/\n 4087,\n/**/\n 4086,\n/**/\n 4085,\n/**/\n 4084,\n/**/\n 4083,\n/**/\n 4082,\n/**/\n 4081,\n/**/\n 4080,\n/**/\n 4079,\n/**/\n 4078,\n/**/\n 4077,\n/**/\n 4076,\n/**/\n 4075,\n/**/\n 4074,\n/**/\n 4073,\n/**/\n 4072,\n/**/\n 4071,\n/**/\n 4070,\n/**/\n 4069,\n/**/\n 4068,\n/**/\n 4067,\n/**/\n 4066,\n/**/\n 4065,\n/**/\n 4064,\n/**/\n 4063,\n/**/\n 4062,\n/**/\n 4061,\n/**/\n 4060,\n/**/\n 4059,\n/**/\n 4058,\n/**/\n 4057,\n/**/\n 4056,\n/**/\n 4055,\n/**/\n 4054,\n/**/\n 4053,\n/**/\n 4052,\n/**/\n 4051,\n/**/\n 4050,\n/**/\n 4049,\n/**/\n 4048,\n/**/\n 4047,\n/**/\n 4046,\n/**/\n 4045,\n/**/\n 4044,\n/**/\n 4043,\n/**/\n 4042,\n/**/\n 4041,\n/**/\n 4040,\n/**/\n 4039,\n/**/\n 4038,\n/**/\n 4037,\n/**/\n 4036,\n/**/\n 4035,\n/**/\n 4034,\n/**/\n 4033,\n/**/\n 4032,\n/**/\n 4031,\n/**/\n 4030,\n/**/\n 4029,\n/**/\n 4028,\n/**/\n 4027,\n/**/\n 4026,\n/**/\n 4025,\n/**/\n 4024,\n/**/\n 4023,\n/**/\n 4022,\n/**/\n 4021,\n/**/\n 4020,\n/**/\n 4019,\n/**/\n 4018,\n/**/\n 4017,\n/**/\n 4016,\n/**/\n 4015,\n/**/\n 4014,\n/**/\n 4013,\n/**/\n 4012,\n/**/\n 4011,\n/**/\n 4010,\n/**/\n 4009,\n/**/\n 4008,\n/**/\n 4007,\n/**/\n 4006,\n/**/\n 4005,\n/**/\n 4004,\n/**/\n 4003,\n/**/\n 4002,\n/**/\n 4001,\n/**/\n 4000,\n/**/\n 3999,\n/**/\n 3998,\n/**/\n 3997,\n/**/\n 3996,\n/**/\n 3995,\n/**/\n 3994,\n/**/\n 3993,\n/**/\n 3992,\n/**/\n 3991,\n/**/\n 3990,\n/**/\n 3989,\n/**/\n 3988,\n/**/\n 3987,\n/**/\n 3986,\n/**/\n 3985,\n/**/\n 3984,\n/**/\n 3983,\n/**/\n 3982,\n/**/\n 3981,\n/**/\n 3980,\n/**/\n 3979,\n/**/\n 3978,\n/**/\n 3977,\n/**/\n 3976,\n/**/\n 3975,\n/**/\n 3974,\n/**/\n 3973,\n/**/\n 3972,\n/**/\n 3971,\n/**/\n 3970,\n/**/\n 3969,\n/**/\n 3968,\n/**/\n 3967,\n/**/\n 3966,\n/**/\n 3965,\n/**/\n 3964,\n/**/\n 3963,\n/**/\n 3962,\n/**/\n 3961,\n/**/\n 3960,\n/**/\n 3959,\n/**/\n 3958,\n/**/\n 3957,\n/**/\n 3956,\n/**/\n 3955,\n/**/\n 3954,\n/**/\n 3953,\n/**/\n 3952,\n/**/\n 3951,\n/**/\n 3950,\n/**/\n 3949,\n/**/\n 3948,\n/**/\n 3947,\n/**/\n 3946,\n/**/\n 3945,\n/**/\n 3944,\n/**/\n 3943,\n/**/\n 3942,\n/**/\n 3941,\n/**/\n 3940,\n/**/\n 3939,\n/**/\n 3938,\n/**/\n 3937,\n/**/\n 3936,\n/**/\n 3935,\n/**/\n 3934,\n/**/\n 3933,\n/**/\n 3932,\n/**/\n 3931,\n/**/\n 3930,\n/**/\n 3929,\n/**/\n 3928,\n/**/\n 3927,\n/**/\n 3926,\n/**/\n 3925,\n/**/\n 3924,\n/**/\n 3923,\n/**/\n 3922,\n/**/\n 3921,\n/**/\n 3920,\n/**/\n 3919,\n/**/\n 3918,\n/**/\n 3917,\n/**/\n 3916,\n/**/\n 3915,\n/**/\n 3914,\n/**/\n 3913,\n/**/\n 3912,\n/**/\n 3911,\n/**/\n 3910,\n/**/\n 3909,\n/**/\n 3908,\n/**/\n 3907,\n/**/\n 3906,\n/**/\n 3905,\n/**/\n 3904,\n/**/\n 3903,\n/**/\n 3902,\n/**/\n 3901,\n/**/\n 3900,\n/**/\n 3899,\n/**/\n 3898,\n/**/\n 3897,\n/**/\n 3896,\n/**/\n 3895,\n/**/\n 3894,\n/**/\n 3893,\n/**/\n 3892,\n/**/\n 3891,\n/**/\n 3890,\n/**/\n 3889,\n/**/\n 3888,\n/**/\n 3887,\n/**/\n 3886,\n/**/\n 3885,\n/**/\n 3884,\n/**/\n 3883,\n/**/\n 3882,\n/**/\n 3881,\n/**/\n 3880,\n/**/\n 3879,\n/**/\n 3878,\n/**/\n 3877,\n/**/\n 3876,\n/**/\n 3875,\n/**/\n 3874,\n/**/\n 3873,\n/**/\n 3872,\n/**/\n 3871,\n/**/\n 3870,\n/**/\n 3869,\n/**/\n 3868,\n/**/\n 3867,\n/**/\n 3866,\n/**/\n 3865,\n/**/\n 3864,\n/**/\n 3863,\n/**/\n 3862,\n/**/\n 3861,\n/**/\n 3860,\n/**/\n 3859,\n/**/\n 3858,\n/**/\n 3857,\n/**/\n 3856,\n/**/\n 3855,\n/**/\n 3854,\n/**/\n 3853,\n/**/\n 3852,\n/**/\n 3851,\n/**/\n 3850,\n/**/\n 3849,\n/**/\n 3848,\n/**/\n 3847,\n/**/\n 3846,\n/**/\n 3845,\n/**/\n 3844,\n/**/\n 3843,\n/**/\n 3842,\n/**/\n 3841,\n/**/\n 3840,\n/**/\n 3839,\n/**/\n 3838,\n/**/\n 3837,\n/**/\n 3836,\n/**/\n 3835,\n/**/\n 3834,\n/**/\n 3833,\n/**/\n 3832,\n/**/\n 3831,\n/**/\n 3830,\n/**/\n 3829,\n/**/\n 3828,\n/**/\n 3827,\n/**/\n 3826,\n/**/\n 3825,\n/**/\n 3824,\n/**/\n 3823,\n/**/\n 3822,\n/**/\n 3821,\n/**/\n 3820,\n/**/\n 3819,\n/**/\n 3818,\n/**/\n 3817,\n/**/\n 3816,\n/**/\n 3815,\n/**/\n 3814,\n/**/\n 3813,\n/**/\n 3812,\n/**/\n 3811,\n/**/\n 3810,\n/**/\n 3809,\n/**/\n 3808,\n/**/\n 3807,\n/**/\n 3806,\n/**/\n 3805,\n/**/\n 3804,\n/**/\n 3803,\n/**/\n 3802,\n/**/\n 3801,\n/**/\n 3800,\n/**/\n 3799,\n/**/\n 3798,\n/**/\n 3797,\n/**/\n 3796,\n/**/\n 3795,\n/**/\n 3794,\n/**/\n 3793,\n/**/\n 3792,\n/**/\n 3791,\n/**/\n 3790,\n/**/\n 3789,\n/**/\n 3788,\n/**/\n 3787,\n/**/\n 3786,\n/**/\n 3785,\n/**/\n 3784,\n/**/\n 3783,\n/**/\n 3782,\n/**/\n 3781,\n/**/\n 3780,\n/**/\n 3779,\n/**/\n 3778,\n/**/\n 3777,\n/**/\n 3776,\n/**/\n 3775,\n/**/\n 3774,\n/**/\n 3773,\n/**/\n 3772,\n/**/\n 3771,\n/**/\n 3770,\n/**/\n 3769,\n/**/\n 3768,\n/**/\n 3767,\n/**/\n 3766,\n/**/\n 3765,\n/**/\n 3764,\n/**/\n 3763,\n/**/\n 3762,\n/**/\n 3761,\n/**/\n 3760,\n/**/\n 3759,\n/**/\n 3758,\n/**/\n 3757,\n/**/\n 3756,\n/**/\n 3755,\n/**/\n 3754,\n/**/\n 3753,\n/**/\n 3752,\n/**/\n 3751,\n/**/\n 3750,\n/**/\n 3749,\n/**/\n 3748,\n/**/\n 3747,\n/**/\n 3746,\n/**/\n 3745,\n/**/\n 3744,\n/**/\n 3743,\n/**/\n 3742,\n/**/\n 3741,\n/**/\n 3740,\n/**/\n 3739,\n/**/\n 3738,\n/**/\n 3737,\n/**/\n 3736,\n/**/\n 3735,\n/**/\n 3734,\n/**/\n 3733,\n/**/\n 3732,\n/**/\n 3731,\n/**/\n 3730,\n/**/\n 3729,\n/**/\n 3728,\n/**/\n 3727,\n/**/\n 3726,\n/**/\n 3725,\n/**/\n 3724,\n/**/\n 3723,\n/**/\n 3722,\n/**/\n 3721,\n/**/\n 3720,\n/**/\n 3719,\n/**/\n 3718,\n/**/\n 3717,\n/**/\n 3716,\n/**/\n 3715,\n/**/\n 3714,\n/**/\n 3713,\n/**/\n 3712,\n/**/\n 3711,\n/**/\n 3710,\n/**/\n 3709,\n/**/\n 3708,\n/**/\n 3707,\n/**/\n 3706,\n/**/\n 3705,\n/**/\n 3704,\n/**/\n 3703,\n/**/\n 3702,\n/**/\n 3701,\n/**/\n 3700,\n/**/\n 3699,\n/**/\n 3698,\n/**/\n 3697,\n/**/\n 3696,\n/**/\n 3695,\n/**/\n 3694,\n/**/\n 3693,\n/**/\n 3692,\n/**/\n 3691,\n/**/\n 3690,\n/**/\n 3689,\n/**/\n 3688,\n/**/\n 3687,\n/**/\n 3686,\n/**/\n 3685,\n/**/\n 3684,\n/**/\n 3683,\n/**/\n 3682,\n/**/\n 3681,\n/**/\n 3680,\n/**/\n 3679,\n/**/\n 3678,\n/**/\n 3677,\n/**/\n 3676,\n/**/\n 3675,\n/**/\n 3674,\n/**/\n 3673,\n/**/\n 3672,\n/**/\n 3671,\n/**/\n 3670,\n/**/\n 3669,\n/**/\n 3668,\n/**/\n 3667,\n/**/\n 3666,\n/**/\n 3665,\n/**/\n 3664,\n/**/\n 3663,\n/**/\n 3662,\n/**/\n 3661,\n/**/\n 3660,\n/**/\n 3659,\n/**/\n 3658,\n/**/\n 3657,\n/**/\n 3656,\n/**/\n 3655,\n/**/\n 3654,\n/**/\n 3653,\n/**/\n 3652,\n/**/\n 3651,\n/**/\n 3650,\n/**/\n 3649,\n/**/\n 3648,\n/**/\n 3647,\n/**/\n 3646,\n/**/\n 3645,\n/**/\n 3644,\n/**/\n 3643,\n/**/\n 3642,\n/**/\n 3641,\n/**/\n 3640,\n/**/\n 3639,\n/**/\n 3638,\n/**/\n 3637,\n/**/\n 3636,\n/**/\n 3635,\n/**/\n 3634,\n/**/\n 3633,\n/**/\n 3632,\n/**/\n 3631,\n/**/\n 3630,\n/**/\n 3629,\n/**/\n 3628,\n/**/\n 3627,\n/**/\n 3626,\n/**/\n 3625,\n/**/\n 3624,\n/**/\n 3623,\n/**/\n 3622,\n/**/\n 3621,\n/**/\n 3620,\n/**/\n 3619,\n/**/\n 3618,\n/**/\n 3617,\n/**/\n 3616,\n/**/\n 3615,\n/**/\n 3614,\n/**/\n 3613,\n/**/\n 3612,\n/**/\n 3611,\n/**/\n 3610,\n/**/\n 3609,\n/**/\n 3608,\n/**/\n 3607,\n/**/\n 3606,\n/**/\n 3605,\n/**/\n 3604,\n/**/\n 3603,\n/**/\n 3602,\n/**/\n 3601,\n/**/\n 3600,\n/**/\n 3599,\n/**/\n 3598,\n/**/\n 3597,\n/**/\n 3596,\n/**/\n 3595,\n/**/\n 3594,\n/**/\n 3593,\n/**/\n 3592,\n/**/\n 3591,\n/**/\n 3590,\n/**/\n 3589,\n/**/\n 3588,\n/**/\n 3587,\n/**/\n 3586,\n/**/\n 3585,\n/**/\n 3584,\n/**/\n 3583,\n/**/\n 3582,\n/**/\n 3581,\n/**/\n 3580,\n/**/\n 3579,\n/**/\n 3578,\n/**/\n 3577,\n/**/\n 3576,\n/**/\n 3575,\n/**/\n 3574,\n/**/\n 3573,\n/**/\n 3572,\n/**/\n 3571,\n/**/\n 3570,\n/**/\n 3569,\n/**/\n 3568,\n/**/\n 3567,\n/**/\n 3566,\n/**/\n 3565,\n/**/\n 3564,\n/**/\n 3563,\n/**/\n 3562,\n/**/\n 3561,\n/**/\n 3560,\n/**/\n 3559,\n/**/\n 3558,\n/**/\n 3557,\n/**/\n 3556,\n/**/\n 3555,\n/**/\n 3554,\n/**/\n 3553,\n/**/\n 3552,\n/**/\n 3551,\n/**/\n 3550,\n/**/\n 3549,\n/**/\n 3548,\n/**/\n 3547,\n/**/\n 3546,\n/**/\n 3545,\n/**/\n 3544,\n/**/\n 3543,\n/**/\n 3542,\n/**/\n 3541,\n/**/\n 3540,\n/**/\n 3539,\n/**/\n 3538,\n/**/\n 3537,\n/**/\n 3536,\n/**/\n 3535,\n/**/\n 3534,\n/**/\n 3533,\n/**/\n 3532,\n/**/\n 3531,\n/**/\n 3530,\n/**/\n 3529,\n/**/\n 3528,\n/**/\n 3527,\n/**/\n 3526,\n/**/\n 3525,\n/**/\n 3524,\n/**/\n 3523,\n/**/\n 3522,\n/**/\n 3521,\n/**/\n 3520,\n/**/\n 3519,\n/**/\n 3518,\n/**/\n 3517,\n/**/\n 3516,\n/**/\n 3515,\n/**/\n 3514,\n/**/\n 3513,\n/**/\n 3512,\n/**/\n 3511,\n/**/\n 3510,\n/**/\n 3509,\n/**/\n 3508,\n/**/\n 3507,\n/**/\n 3506,\n/**/\n 3505,\n/**/\n 3504,\n/**/\n 3503,\n/**/\n 3502,\n/**/\n 3501,\n/**/\n 3500,\n/**/\n 3499,\n/**/\n 3498,\n/**/\n 3497,\n/**/\n 3496,\n/**/\n 3495,\n/**/\n 3494,\n/**/\n 3493,\n/**/\n 3492,\n/**/\n 3491,\n/**/\n 3490,\n/**/\n 3489,\n/**/\n 3488,\n/**/\n 3487,\n/**/\n 3486,\n/**/\n 3485,\n/**/\n 3484,\n/**/\n 3483,\n/**/\n 3482,\n/**/\n 3481,\n/**/\n 3480,\n/**/\n 3479,\n/**/\n 3478,\n/**/\n 3477,\n/**/\n 3476,\n/**/\n 3475,\n/**/\n 3474,\n/**/\n 3473,\n/**/\n 3472,\n/**/\n 3471,\n/**/\n 3470,\n/**/\n 3469,\n/**/\n 3468,\n/**/\n 3467,\n/**/\n 3466,\n/**/\n 3465,\n/**/\n 3464,\n/**/\n 3463,\n/**/\n 3462,\n/**/\n 3461,\n/**/\n 3460,\n/**/\n 3459,\n/**/\n 3458,\n/**/\n 3457,\n/**/\n 3456,\n/**/\n 3455,\n/**/\n 3454,\n/**/\n 3453,\n/**/\n 3452,\n/**/\n 3451,\n/**/\n 3450,\n/**/\n 3449,\n/**/\n 3448,\n/**/\n 3447,\n/**/\n 3446,\n/**/\n 3445,\n/**/\n 3444,\n/**/\n 3443,\n/**/\n 3442,\n/**/\n 3441,\n/**/\n 3440,\n/**/\n 3439,\n/**/\n 3438,\n/**/\n 3437,\n/**/\n 3436,\n/**/\n 3435,\n/**/\n 3434,\n/**/\n 3433,\n/**/\n 3432,\n/**/\n 3431,\n/**/\n 3430,\n/**/\n 3429,\n/**/\n 3428,\n/**/\n 3427,\n/**/\n 3426,\n/**/\n 3425,\n/**/\n 3424,\n/**/\n 3423,\n/**/\n 3422,\n/**/\n 3421,\n/**/\n 3420,\n/**/\n 3419,\n/**/\n 3418,\n/**/\n 3417,\n/**/\n 3416,\n/**/\n 3415,\n/**/\n 3414,\n/**/\n 3413,\n/**/\n 3412,\n/**/\n 3411,\n/**/\n 3410,\n/**/\n 3409,\n/**/\n 3408,\n/**/\n 3407,\n/**/\n 3406,\n/**/\n 3405,\n/**/\n 3404,\n/**/\n 3403,\n/**/\n 3402,\n/**/\n 3401,\n/**/\n 3400,\n/**/\n 3399,\n/**/\n 3398,\n/**/\n 3397,\n/**/\n 3396,\n/**/\n 3395,\n/**/\n 3394,\n/**/\n 3393,\n/**/\n 3392,\n/**/\n 3391,\n/**/\n 3390,\n/**/\n 3389,\n/**/\n 3388,\n/**/\n 3387,\n/**/\n 3386,\n/**/\n 3385,\n/**/\n 3384,\n/**/\n 3383,\n/**/\n 3382,\n/**/\n 3381,\n/**/\n 3380,\n/**/\n 3379,\n/**/\n 3378,\n/**/\n 3377,\n/**/\n 3376,\n/**/\n 3375,\n/**/\n 3374,\n/**/\n 3373,\n/**/\n 3372,\n/**/\n 3371,\n/**/\n 3370,\n/**/\n 3369,\n/**/\n 3368,\n/**/\n 3367,\n/**/\n 3366,\n/**/\n 3365,\n/**/\n 3364,\n/**/\n 3363,\n/**/\n 3362,\n/**/\n 3361,\n/**/\n 3360,\n/**/\n 3359,\n/**/\n 3358,\n/**/\n 3357,\n/**/\n 3356,\n/**/\n 3355,\n/**/\n 3354,\n/**/\n 3353,\n/**/\n 3352,\n/**/\n 3351,\n/**/\n 3350,\n/**/\n 3349,\n/**/\n 3348,\n/**/\n 3347,\n/**/\n 3346,\n/**/\n 3345,\n/**/\n 3344,\n/**/\n 3343,\n/**/\n 3342,\n/**/\n 3341,\n/**/\n 3340,\n/**/\n 3339,\n/**/\n 3338,\n/**/\n 3337,\n/**/\n 3336,\n/**/\n 3335,\n/**/\n 3334,\n/**/\n 3333,\n/**/\n 3332,\n/**/\n 3331,\n/**/\n 3330,\n/**/\n 3329,\n/**/\n 3328,\n/**/\n 3327,\n/**/\n 3326,\n/**/\n 3325,\n/**/\n 3324,\n/**/\n 3323,\n/**/\n 3322,\n/**/\n 3321,\n/**/\n 3320,\n/**/\n 3319,\n/**/\n 3318,\n/**/\n 3317,\n/**/\n 3316,\n/**/\n 3315,\n/**/\n 3314,\n/**/\n 3313,\n/**/\n 3312,\n/**/\n 3311,\n/**/\n 3310,\n/**/\n 3309,\n/**/\n 3308,\n/**/\n 3307,\n/**/\n 3306,\n/**/\n 3305,\n/**/\n 3304,\n/**/\n 3303,\n/**/\n 3302,\n/**/\n 3301,\n/**/\n 3300,\n/**/\n 3299,\n/**/\n 3298,\n/**/\n 3297,\n/**/\n 3296,\n/**/\n 3295,\n/**/\n 3294,\n/**/\n 3293,\n/**/\n 3292,\n/**/\n 3291,\n/**/\n 3290,\n/**/\n 3289,\n/**/\n 3288,\n/**/\n 3287,\n/**/\n 3286,\n/**/\n 3285,\n/**/\n 3284,\n/**/\n 3283,\n/**/\n 3282,\n/**/\n 3281,\n/**/\n 3280,\n/**/\n 3279,\n/**/\n 3278,\n/**/\n 3277,\n/**/\n 3276,\n/**/\n 3275,\n/**/\n 3274,\n/**/\n 3273,\n/**/\n 3272,\n/**/\n 3271,\n/**/\n 3270,\n/**/\n 3269,\n/**/\n 3268,\n/**/\n 3267,\n/**/\n 3266,\n/**/\n 3265,\n/**/\n 3264,\n/**/\n 3263,\n/**/\n 3262,\n/**/\n 3261,\n/**/\n 3260,\n/**/\n 3259,\n/**/\n 3258,\n/**/\n 3257,\n/**/\n 3256,\n/**/\n 3255,\n/**/\n 3254,\n/**/\n 3253,\n/**/\n 3252,\n/**/\n 3251,\n/**/\n 3250,\n/**/\n 3249,\n/**/\n 3248,\n/**/\n 3247,\n/**/\n 3246,\n/**/\n 3245,\n/**/\n 3244,\n/**/\n 3243,\n/**/\n 3242,\n/**/\n 3241,\n/**/\n 3240,\n/**/\n 3239,\n/**/\n 3238,\n/**/\n 3237,\n/**/\n 3236,\n/**/\n 3235,\n/**/\n 3234,\n/**/\n 3233,\n/**/\n 3232,\n/**/\n 3231,\n/**/\n 3230,\n/**/\n 3229,\n/**/\n 3228,\n/**/\n 3227,\n/**/\n 3226,\n/**/\n 3225,\n/**/\n 3224,\n/**/\n 3223,\n/**/\n 3222,\n/**/\n 3221,\n/**/\n 3220,\n/**/\n 3219,\n/**/\n 3218,\n/**/\n 3217,\n/**/\n 3216,\n/**/\n 3215,\n/**/\n 3214,\n/**/\n 3213,\n/**/\n 3212,\n/**/\n 3211,\n/**/\n 3210,\n/**/\n 3209,\n/**/\n 3208,\n/**/\n 3207,\n/**/\n 3206,\n/**/\n 3205,\n/**/\n 3204,\n/**/\n 3203,\n/**/\n 3202,\n/**/\n 3201,\n/**/\n 3200,\n/**/\n 3199,\n/**/\n 3198,\n/**/\n 3197,\n/**/\n 3196,\n/**/\n 3195,\n/**/\n 3194,\n/**/\n 3193,\n/**/\n 3192,\n/**/\n 3191,\n/**/\n 3190,\n/**/\n 3189,\n/**/\n 3188,\n/**/\n 3187,\n/**/\n 3186,\n/**/\n 3185,\n/**/\n 3184,\n/**/\n 3183,\n/**/\n 3182,\n/**/\n 3181,\n/**/\n 3180,\n/**/\n 3179,\n/**/\n 3178,\n/**/\n 3177,\n/**/\n 3176,\n/**/\n 3175,\n/**/\n 3174,\n/**/\n 3173,\n/**/\n 3172,\n/**/\n 3171,\n/**/\n 3170,\n/**/\n 3169,\n/**/\n 3168,\n/**/\n 3167,\n/**/\n 3166,\n/**/\n 3165,\n/**/\n 3164,\n/**/\n 3163,\n/**/\n 3162,\n/**/\n 3161,\n/**/\n 3160,\n/**/\n 3159,\n/**/\n 3158,\n/**/\n 3157,\n/**/\n 3156,\n/**/\n 3155,\n/**/\n 3154,\n/**/\n 3153,\n/**/\n 3152,\n/**/\n 3151,\n/**/\n 3150,\n/**/\n 3149,\n/**/\n 3148,\n/**/\n 3147,\n/**/\n 3146,\n/**/\n 3145,\n/**/\n 3144,\n/**/\n 3143,\n/**/\n 3142,\n/**/\n 3141,\n/**/\n 3140,\n/**/\n 3139,\n/**/\n 3138,\n/**/\n 3137,\n/**/\n 3136,\n/**/\n 3135,\n/**/\n 3134,\n/**/\n 3133,\n/**/\n 3132,\n/**/\n 3131,\n/**/\n 3130,\n/**/\n 3129,\n/**/\n 3128,\n/**/\n 3127,\n/**/\n 3126,\n/**/\n 3125,\n/**/\n 3124,\n/**/\n 3123,\n/**/\n 3122,\n/**/\n 3121,\n/**/\n 3120,\n/**/\n 3119,\n/**/\n 3118,\n/**/\n 3117,\n/**/\n 3116,\n/**/\n 3115,\n/**/\n 3114,\n/**/\n 3113,\n/**/\n 3112,\n/**/\n 3111,\n/**/\n 3110,\n/**/\n 3109,\n/**/\n 3108,\n/**/\n 3107,\n/**/\n 3106,\n/**/\n 3105,\n/**/\n 3104,\n/**/\n 3103,\n/**/\n 3102,\n/**/\n 3101,\n/**/\n 3100,\n/**/\n 3099,\n/**/\n 3098,\n/**/\n 3097,\n/**/\n 3096,\n/**/\n 3095,\n/**/\n 3094,\n/**/\n 3093,\n/**/\n 3092,\n/**/\n 3091,\n/**/\n 3090,\n/**/\n 3089,\n/**/\n 3088,\n/**/\n 3087,\n/**/\n 3086,\n/**/\n 3085,\n/**/\n 3084,\n/**/\n 3083,\n/**/\n 3082,\n/**/\n 3081,\n/**/\n 3080,\n/**/\n 3079,\n/**/\n 3078,\n/**/\n 3077,\n/**/\n 3076,\n/**/\n 3075,\n/**/\n 3074,\n/**/\n 3073,\n/**/\n 3072,\n/**/\n 3071,\n/**/\n 3070,\n/**/\n 3069,\n/**/\n 3068,\n/**/\n 3067,\n/**/\n 3066,\n/**/\n 3065,\n/**/\n 3064,\n/**/\n 3063,\n/**/\n 3062,\n/**/\n 3061,\n/**/\n 3060,\n/**/\n 3059,\n/**/\n 3058,\n/**/\n 3057,\n/**/\n 3056,\n/**/\n 3055,\n/**/\n 3054,\n/**/\n 3053,\n/**/\n 3052,\n/**/\n 3051,\n/**/\n 3050,\n/**/\n 3049,\n/**/\n 3048,\n/**/\n 3047,\n/**/\n 3046,\n/**/\n 3045,\n/**/\n 3044,\n/**/\n 3043,\n/**/\n 3042,\n/**/\n 3041,\n/**/\n 3040,\n/**/\n 3039,\n/**/\n 3038,\n/**/\n 3037,\n/**/\n 3036,\n/**/\n 3035,\n/**/\n 3034,\n/**/\n 3033,\n/**/\n 3032,\n/**/\n 3031,\n/**/\n 3030,\n/**/\n 3029,\n/**/\n 3028,\n/**/\n 3027,\n/**/\n 3026,\n/**/\n 3025,\n/**/\n 3024,\n/**/\n 3023,\n/**/\n 3022,\n/**/\n 3021,\n/**/\n 3020,\n/**/\n 3019,\n/**/\n 3018,\n/**/\n 3017,\n/**/\n 3016,\n/**/\n 3015,\n/**/\n 3014,\n/**/\n 3013,\n/**/\n 3012,\n/**/\n 3011,\n/**/\n 3010,\n/**/\n 3009,\n/**/\n 3008,\n/**/\n 3007,\n/**/\n 3006,\n/**/\n 3005,\n/**/\n 3004,\n/**/\n 3003,\n/**/\n 3002,\n/**/\n 3001,\n/**/\n 3000,\n/**/\n 2999,\n/**/\n 2998,\n/**/\n 2997,\n/**/\n 2996,\n/**/\n 2995,\n/**/\n 2994,\n/**/\n 2993,\n/**/\n 2992,\n/**/\n 2991,\n/**/\n 2990,\n/**/\n 2989,\n/**/\n 2988,\n/**/\n 2987,\n/**/\n 2986,\n/**/\n 2985,\n/**/\n 2984,\n/**/\n 2983,\n/**/\n 2982,\n/**/\n 2981,\n/**/\n 2980,\n/**/\n 2979,\n/**/\n 2978,\n/**/\n 2977,\n/**/\n 2976,\n/**/\n 2975,\n/**/\n 2974,\n/**/\n 2973,\n/**/\n 2972,\n/**/\n 2971,\n/**/\n 2970,\n/**/\n 2969,\n/**/\n 2968,\n/**/\n 2967,\n/**/\n 2966,\n/**/\n 2965,\n/**/\n 2964,\n/**/\n 2963,\n/**/\n 2962,\n/**/\n 2961,\n/**/\n 2960,\n/**/\n 2959,\n/**/\n 2958,\n/**/\n 2957,\n/**/\n 2956,\n/**/\n 2955,\n/**/\n 2954,\n/**/\n 2953,\n/**/\n 2952,\n/**/\n 2951,\n/**/\n 2950,\n/**/\n 2949,\n/**/\n 2948,\n/**/\n 2947,\n/**/\n 2946,\n/**/\n 2945,\n/**/\n 2944,\n/**/\n 2943,\n/**/\n 2942,\n/**/\n 2941,\n/**/\n 2940,\n/**/\n 2939,\n/**/\n 2938,\n/**/\n 2937,\n/**/\n 2936,\n/**/\n 2935,\n/**/\n 2934,\n/**/\n 2933,\n/**/\n 2932,\n/**/\n 2931,\n/**/\n 2930,\n/**/\n 2929,\n/**/\n 2928,\n/**/\n 2927,\n/**/\n 2926,\n/**/\n 2925,\n/**/\n 2924,\n/**/\n 2923,\n/**/\n 2922,\n/**/\n 2921,\n/**/\n 2920,\n/**/\n 2919,\n/**/\n 2918,\n/**/\n 2917,\n/**/\n 2916,\n/**/\n 2915,\n/**/\n 2914,\n/**/\n 2913,\n/**/\n 2912,\n/**/\n 2911,\n/**/\n 2910,\n/**/\n 2909,\n/**/\n 2908,\n/**/\n 2907,\n/**/\n 2906,\n/**/\n 2905,\n/**/\n 2904,\n/**/\n 2903,\n/**/\n 2902,\n/**/\n 2901,\n/**/\n 2900,\n/**/\n 2899,\n/**/\n 2898,\n/**/\n 2897,\n/**/\n 2896,\n/**/\n 2895,\n/**/\n 2894,\n/**/\n 2893,\n/**/\n 2892,\n/**/\n 2891,\n/**/\n 2890,\n/**/\n 2889,\n/**/\n 2888,\n/**/\n 2887,\n/**/\n 2886,\n/**/\n 2885,\n/**/\n 2884,\n/**/\n 2883,\n/**/\n 2882,\n/**/\n 2881,\n/**/\n 2880,\n/**/\n 2879,\n/**/\n 2878,\n/**/\n 2877,\n/**/\n 2876,\n/**/\n 2875,\n/**/\n 2874,\n/**/\n 2873,\n/**/\n 2872,\n/**/\n 2871,\n/**/\n 2870,\n/**/\n 2869,\n/**/\n 2868,\n/**/\n 2867,\n/**/\n 2866,\n/**/\n 2865,\n/**/\n 2864,\n/**/\n 2863,\n/**/\n 2862,\n/**/\n 2861,\n/**/\n 2860,\n/**/\n 2859,\n/**/\n 2858,\n/**/\n 2857,\n/**/\n 2856,\n/**/\n 2855,\n/**/\n 2854,\n/**/\n 2853,\n/**/\n 2852,\n/**/\n 2851,\n/**/\n 2850,\n/**/\n 2849,\n/**/\n 2848,\n/**/\n 2847,\n/**/\n 2846,\n/**/\n 2845,\n/**/\n 2844,\n/**/\n 2843,\n/**/\n 2842,\n/**/\n 2841,\n/**/\n 2840,\n/**/\n 2839,\n/**/\n 2838,\n/**/\n 2837,\n/**/\n 2836,\n/**/\n 2835,\n/**/\n 2834,\n/**/\n 2833,\n/**/\n 2832,\n/**/\n 2831,\n/**/\n 2830,\n/**/\n 2829,\n/**/\n 2828,\n/**/\n 2827,\n/**/\n 2826,\n/**/\n 2825,\n/**/\n 2824,\n/**/\n 2823,\n/**/\n 2822,\n/**/\n 2821,\n/**/\n 2820,\n/**/\n 2819,\n/**/\n 2818,\n/**/\n 2817,\n/**/\n 2816,\n/**/\n 2815,\n/**/\n 2814,\n/**/\n 2813,\n/**/\n 2812,\n/**/\n 2811,\n/**/\n 2810,\n/**/\n 2809,\n/**/\n 2808,\n/**/\n 2807,\n/**/\n 2806,\n/**/\n 2805,\n/**/\n 2804,\n/**/\n 2803,\n/**/\n 2802,\n/**/\n 2801,\n/**/\n 2800,\n/**/\n 2799,\n/**/\n 2798,\n/**/\n 2797,\n/**/\n 2796,\n/**/\n 2795,\n/**/\n 2794,\n/**/\n 2793,\n/**/\n 2792,\n/**/\n 2791,\n/**/\n 2790,\n/**/\n 2789,\n/**/\n 2788,\n/**/\n 2787,\n/**/\n 2786,\n/**/\n 2785,\n/**/\n 2784,\n/**/\n 2783,\n/**/\n 2782,\n/**/\n 2781,\n/**/\n 2780,\n/**/\n 2779,\n/**/\n 2778,\n/**/\n 2777,\n/**/\n 2776,\n/**/\n 2775,\n/**/\n 2774,\n/**/\n 2773,\n/**/\n 2772,\n/**/\n 2771,\n/**/\n 2770,\n/**/\n 2769,\n/**/\n 2768,\n/**/\n 2767,\n/**/\n 2766,\n/**/\n 2765,\n/**/\n 2764,\n/**/\n 2763,\n/**/\n 2762,\n/**/\n 2761,\n/**/\n 2760,\n/**/\n 2759,\n/**/\n 2758,\n/**/\n 2757,\n/**/\n 2756,\n/**/\n 2755,\n/**/\n 2754,\n/**/\n 2753,\n/**/\n 2752,\n/**/\n 2751,\n/**/\n 2750,\n/**/\n 2749,\n/**/\n 2748,\n/**/\n 2747,\n/**/\n 2746,\n/**/\n 2745,\n/**/\n 2744,\n/**/\n 2743,\n/**/\n 2742,\n/**/\n 2741,\n/**/\n 2740,\n/**/\n 2739,\n/**/\n 2738,\n/**/\n 2737,\n/**/\n 2736,\n/**/\n 2735,\n/**/\n 2734,\n/**/\n 2733,\n/**/\n 2732,\n/**/\n 2731,\n/**/\n 2730,\n/**/\n 2729,\n/**/\n 2728,\n/**/\n 2727,\n/**/\n 2726,\n/**/\n 2725,\n/**/\n 2724,\n/**/\n 2723,\n/**/\n 2722,\n/**/\n 2721,\n/**/\n 2720,\n/**/\n 2719,\n/**/\n 2718,\n/**/\n 2717,\n/**/\n 2716,\n/**/\n 2715,\n/**/\n 2714,\n/**/\n 2713,\n/**/\n 2712,\n/**/\n 2711,\n/**/\n 2710,\n/**/\n 2709,\n/**/\n 2708,\n/**/\n 2707,\n/**/\n 2706,\n/**/\n 2705,\n/**/\n 2704,\n/**/\n 2703,\n/**/\n 2702,\n/**/\n 2701,\n/**/\n 2700,\n/**/\n 2699,\n/**/\n 2698,\n/**/\n 2697,\n/**/\n 2696,\n/**/\n 2695,\n/**/\n 2694,\n/**/\n 2693,\n/**/\n 2692,\n/**/\n 2691,\n/**/\n 2690,\n/**/\n 2689,\n/**/\n 2688,\n/**/\n 2687,\n/**/\n 2686,\n/**/\n 2685,\n/**/\n 2684,\n/**/\n 2683,\n/**/\n 2682,\n/**/\n 2681,\n/**/\n 2680,\n/**/\n 2679,\n/**/\n 2678,\n/**/\n 2677,\n/**/\n 2676,\n/**/\n 2675,\n/**/\n 2674,\n/**/\n 2673,\n/**/\n 2672,\n/**/\n 2671,\n/**/\n 2670,\n/**/\n 2669,\n/**/\n 2668,\n/**/\n 2667,\n/**/\n 2666,\n/**/\n 2665,\n/**/\n 2664,\n/**/\n 2663,\n/**/\n 2662,\n/**/\n 2661,\n/**/\n 2660,\n/**/\n 2659,\n/**/\n 2658,\n/**/\n 2657,\n/**/\n 2656,\n/**/\n 2655,\n/**/\n 2654,\n/**/\n 2653,\n/**/\n 2652,\n/**/\n 2651,\n/**/\n 2650,\n/**/\n 2649,\n/**/\n 2648,\n/**/\n 2647,\n/**/\n 2646,\n/**/\n 2645,\n/**/\n 2644,\n/**/\n 2643,\n/**/\n 2642,\n/**/\n 2641,\n/**/\n 2640,\n/**/\n 2639,\n/**/\n 2638,\n/**/\n 2637,\n/**/\n 2636,\n/**/\n 2635,\n/**/\n 2634,\n/**/\n 2633,\n/**/\n 2632,\n/**/\n 2631,\n/**/\n 2630,\n/**/\n 2629,\n/**/\n 2628,\n/**/\n 2627,\n/**/\n 2626,\n/**/\n 2625,\n/**/\n 2624,\n/**/\n 2623,\n/**/\n 2622,\n/**/\n 2621,\n/**/\n 2620,\n/**/\n 2619,\n/**/\n 2618,\n/**/\n 2617,\n/**/\n 2616,\n/**/\n 2615,\n/**/\n 2614,\n/**/\n 2613,\n/**/\n 2612,\n/**/\n 2611,\n/**/\n 2610,\n/**/\n 2609,\n/**/\n 2608,\n/**/\n 2607,\n/**/\n 2606,\n/**/\n 2605,\n/**/\n 2604,\n/**/\n 2603,\n/**/\n 2602,\n/**/\n 2601,\n/**/\n 2600,\n/**/\n 2599,\n/**/\n 2598,\n/**/\n 2597,\n/**/\n 2596,\n/**/\n 2595,\n/**/\n 2594,\n/**/\n 2593,\n/**/\n 2592,\n/**/\n 2591,\n/**/\n 2590,\n/**/\n 2589,\n/**/\n 2588,\n/**/\n 2587,\n/**/\n 2586,\n/**/\n 2585,\n/**/\n 2584,\n/**/\n 2583,\n/**/\n 2582,\n/**/\n 2581,\n/**/\n 2580,\n/**/\n 2579,\n/**/\n 2578,\n/**/\n 2577,\n/**/\n 2576,\n/**/\n 2575,\n/**/\n 2574,\n/**/\n 2573,\n/**/\n 2572,\n/**/\n 2571,\n/**/\n 2570,\n/**/\n 2569,\n/**/\n 2568,\n/**/\n 2567,\n/**/\n 2566,\n/**/\n 2565,\n/**/\n 2564,\n/**/\n 2563,\n/**/\n 2562,\n/**/\n 2561,\n/**/\n 2560,\n/**/\n 2559,\n/**/\n 2558,\n/**/\n 2557,\n/**/\n 2556,\n/**/\n 2555,\n/**/\n 2554,\n/**/\n 2553,\n/**/\n 2552,\n/**/\n 2551,\n/**/\n 2550,\n/**/\n 2549,\n/**/\n 2548,\n/**/\n 2547,\n/**/\n 2546,\n/**/\n 2545,\n/**/\n 2544,\n/**/\n 2543,\n/**/\n 2542,\n/**/\n 2541,\n/**/\n 2540,\n/**/\n 2539,\n/**/\n 2538,\n/**/\n 2537,\n/**/\n 2536,\n/**/\n 2535,\n/**/\n 2534,\n/**/\n 2533,\n/**/\n 2532,\n/**/\n 2531,\n/**/\n 2530,\n/**/\n 2529,\n/**/\n 2528,\n/**/\n 2527,\n/**/\n 2526,\n/**/\n 2525,\n/**/\n 2524,\n/**/\n 2523,\n/**/\n 2522,\n/**/\n 2521,\n/**/\n 2520,\n/**/\n 2519,\n/**/\n 2518,\n/**/\n 2517,\n/**/\n 2516,\n/**/\n 2515,\n/**/\n 2514,\n/**/\n 2513,\n/**/\n 2512,\n/**/\n 2511,\n/**/\n 2510,\n/**/\n 2509,\n/**/\n 2508,\n/**/\n 2507,\n/**/\n 2506,\n/**/\n 2505,\n/**/\n 2504,\n/**/\n 2503,\n/**/\n 2502,\n/**/\n 2501,\n/**/\n 2500,\n/**/\n 2499,\n/**/\n 2498,\n/**/\n 2497,\n/**/\n 2496,\n/**/\n 2495,\n/**/\n 2494,\n/**/\n 2493,\n/**/\n 2492,\n/**/\n 2491,\n/**/\n 2490,\n/**/\n 2489,\n/**/\n 2488,\n/**/\n 2487,\n/**/\n 2486,\n/**/\n 2485,\n/**/\n 2484,\n/**/\n 2483,\n/**/\n 2482,\n/**/\n 2481,\n/**/\n 2480,\n/**/\n 2479,\n/**/\n 2478,\n/**/\n 2477,\n/**/\n 2476,\n/**/\n 2475,\n/**/\n 2474,\n/**/\n 2473,\n/**/\n 2472,\n/**/\n 2471,\n/**/\n 2470,\n/**/\n 2469,\n/**/\n 2468,\n/**/\n 2467,\n/**/\n 2466,\n/**/\n 2465,\n/**/\n 2464,\n/**/\n 2463,\n/**/\n 2462,\n/**/\n 2461,\n/**/\n 2460,\n/**/\n 2459,\n/**/\n 2458,\n/**/\n 2457,\n/**/\n 2456,\n/**/\n 2455,\n/**/\n 2454,\n/**/\n 2453,\n/**/\n 2452,\n/**/\n 2451,\n/**/\n 2450,\n/**/\n 2449,\n/**/\n 2448,\n/**/\n 2447,\n/**/\n 2446,\n/**/\n 2445,\n/**/\n 2444,\n/**/\n 2443,\n/**/\n 2442,\n/**/\n 2441,\n/**/\n 2440,\n/**/\n 2439,\n/**/\n 2438,\n/**/\n 2437,\n/**/\n 2436,\n/**/\n 2435,\n/**/\n 2434,\n/**/\n 2433,\n/**/\n 2432,\n/**/\n 2431,\n/**/\n 2430,\n/**/\n 2429,\n/**/\n 2428,\n/**/\n 2427,\n/**/\n 2426,\n/**/\n 2425,\n/**/\n 2424,\n/**/\n 2423,\n/**/\n 2422,\n/**/\n 2421,\n/**/\n 2420,\n/**/\n 2419,\n/**/\n 2418,\n/**/\n 2417,\n/**/\n 2416,\n/**/\n 2415,\n/**/\n 2414,\n/**/\n 2413,\n/**/\n 2412,\n/**/\n 2411,\n/**/\n 2410,\n/**/\n 2409,\n/**/\n 2408,\n/**/\n 2407,\n/**/\n 2406,\n/**/\n 2405,\n/**/\n 2404,\n/**/\n 2403,\n/**/\n 2402,\n/**/\n 2401,\n/**/\n 2400,\n/**/\n 2399,\n/**/\n 2398,\n/**/\n 2397,\n/**/\n 2396,\n/**/\n 2395,\n/**/\n 2394,\n/**/\n 2393,\n/**/\n 2392,\n/**/\n 2391,\n/**/\n 2390,\n/**/\n 2389,\n/**/\n 2388,\n/**/\n 2387,\n/**/\n 2386,\n/**/\n 2385,\n/**/\n 2384,\n/**/\n 2383,\n/**/\n 2382,\n/**/\n 2381,\n/**/\n 2380,\n/**/\n 2379,\n/**/\n 2378,\n/**/\n 2377,\n/**/\n 2376,\n/**/\n 2375,\n/**/\n 2374,\n/**/\n 2373,\n/**/\n 2372,\n/**/\n 2371,\n/**/\n 2370,\n/**/\n 2369,\n/**/\n 2368,\n/**/\n 2367,\n/**/\n 2366,\n/**/\n 2365,\n/**/\n 2364,\n/**/\n 2363,\n/**/\n 2362,\n/**/\n 2361,\n/**/\n 2360,\n/**/\n 2359,\n/**/\n 2358,\n/**/\n 2357,\n/**/\n 2356,\n/**/\n 2355,\n/**/\n 2354,\n/**/\n 2353,\n/**/\n 2352,\n/**/\n 2351,\n/**/\n 2350,\n/**/\n 2349,\n/**/\n 2348,\n/**/\n 2347,\n/**/\n 2346,\n/**/\n 2345,\n/**/\n 2344,\n/**/\n 2343,\n/**/\n 2342,\n/**/\n 2341,\n/**/\n 2340,\n/**/\n 2339,\n/**/\n 2338,\n/**/\n 2337,\n/**/\n 2336,\n/**/\n 2335,\n/**/\n 2334,\n/**/\n 2333,\n/**/\n 2332,\n/**/\n 2331,\n/**/\n 2330,\n/**/\n 2329,\n/**/\n 2328,\n/**/\n 2327,\n/**/\n 2326,\n/**/\n 2325,\n/**/\n 2324,\n/**/\n 2323,\n/**/\n 2322,\n/**/\n 2321,\n/**/\n 2320,\n/**/\n 2319,\n/**/\n 2318,\n/**/\n 2317,\n/**/\n 2316,\n/**/\n 2315,\n/**/\n 2314,\n/**/\n 2313,\n/**/\n 2312,\n/**/\n 2311,\n/**/\n 2310,\n/**/\n 2309,\n/**/\n 2308,\n/**/\n 2307,\n/**/\n 2306,\n/**/\n 2305,\n/**/\n 2304,\n/**/\n 2303,\n/**/\n 2302,\n/**/\n 2301,\n/**/\n 2300,\n/**/\n 2299,\n/**/\n 2298,\n/**/\n 2297,\n/**/\n 2296,\n/**/\n 2295,\n/**/\n 2294,\n/**/\n 2293,\n/**/\n 2292,\n/**/\n 2291,\n/**/\n 2290,\n/**/\n 2289,\n/**/\n 2288,\n/**/\n 2287,\n/**/\n 2286,\n/**/\n 2285,\n/**/\n 2284,\n/**/\n 2283,\n/**/\n 2282,\n/**/\n 2281,\n/**/\n 2280,\n/**/\n 2279,\n/**/\n 2278,\n/**/\n 2277,\n/**/\n 2276,\n/**/\n 2275,\n/**/\n 2274,\n/**/\n 2273,\n/**/\n 2272,\n/**/\n 2271,\n/**/\n 2270,\n/**/\n 2269,\n/**/\n 2268,\n/**/\n 2267,\n/**/\n 2266,\n/**/\n 2265,\n/**/\n 2264,\n/**/\n 2263,\n/**/\n 2262,\n/**/\n 2261,\n/**/\n 2260,\n/**/\n 2259,\n/**/\n 2258,\n/**/\n 2257,\n/**/\n 2256,\n/**/\n 2255,\n/**/\n 2254,\n/**/\n 2253,\n/**/\n 2252,\n/**/\n 2251,\n/**/\n 2250,\n/**/\n 2249,\n/**/\n 2248,\n/**/\n 2247,\n/**/\n 2246,\n/**/\n 2245,\n/**/\n 2244,\n/**/\n 2243,\n/**/\n 2242,\n/**/\n 2241,\n/**/\n 2240,\n/**/\n 2239,\n/**/\n 2238,\n/**/\n 2237,\n/**/\n 2236,\n/**/\n 2235,\n/**/\n 2234,\n/**/\n 2233,\n/**/\n 2232,\n/**/\n 2231,\n/**/\n 2230,\n/**/\n 2229,\n/**/\n 2228,\n/**/\n 2227,\n/**/\n 2226,\n/**/\n 2225,\n/**/\n 2224,\n/**/\n 2223,\n/**/\n 2222,\n/**/\n 2221,\n/**/\n 2220,\n/**/\n 2219,\n/**/\n 2218,\n/**/\n 2217,\n/**/\n 2216,\n/**/\n 2215,\n/**/\n 2214,\n/**/\n 2213,\n/**/\n 2212,\n/**/\n 2211,\n/**/\n 2210,\n/**/\n 2209,\n/**/\n 2208,\n/**/\n 2207,\n/**/\n 2206,\n/**/\n 2205,\n/**/\n 2204,\n/**/\n 2203,\n/**/\n 2202,\n/**/\n 2201,\n/**/\n 2200,\n/**/\n 2199,\n/**/\n 2198,\n/**/\n 2197,\n/**/\n 2196,\n/**/\n 2195,\n/**/\n 2194,\n/**/\n 2193,\n/**/\n 2192,\n/**/\n 2191,\n/**/\n 2190,\n/**/\n 2189,\n/**/\n 2188,\n/**/\n 2187,\n/**/\n 2186,\n/**/\n 2185,\n/**/\n 2184,\n/**/\n 2183,\n/**/\n 2182,\n/**/\n 2181,\n/**/\n 2180,\n/**/\n 2179,\n/**/\n 2178,\n/**/\n 2177,\n/**/\n 2176,\n/**/\n 2175,\n/**/\n 2174,\n/**/\n 2173,\n/**/\n 2172,\n/**/\n 2171,\n/**/\n 2170,\n/**/\n 2169,\n/**/\n 2168,\n/**/\n 2167,\n/**/\n 2166,\n/**/\n 2165,\n/**/\n 2164,\n/**/\n 2163,\n/**/\n 2162,\n/**/\n 2161,\n/**/\n 2160,\n/**/\n 2159,\n/**/\n 2158,\n/**/\n 2157,\n/**/\n 2156,\n/**/\n 2155,\n/**/\n 2154,\n/**/\n 2153,\n/**/\n 2152,\n/**/\n 2151,\n/**/\n 2150,\n/**/\n 2149,\n/**/\n 2148,\n/**/\n 2147,\n/**/\n 2146,\n/**/\n 2145,\n/**/\n 2144,\n/**/\n 2143,\n/**/\n 2142,\n/**/\n 2141,\n/**/\n 2140,\n/**/\n 2139,\n/**/\n 2138,\n/**/\n 2137,\n/**/\n 2136,\n/**/\n 2135,\n/**/\n 2134,\n/**/\n 2133,\n/**/\n 2132,\n/**/\n 2131,\n/**/\n 2130,\n/**/\n 2129,\n/**/\n 2128,\n/**/\n 2127,\n/**/\n 2126,\n/**/\n 2125,\n/**/\n 2124,\n/**/\n 2123,\n/**/\n 2122,\n/**/\n 2121,\n/**/\n 2120,\n/**/\n 2119,\n/**/\n 2118,\n/**/\n 2117,\n/**/\n 2116,\n/**/\n 2115,\n/**/\n 2114,\n/**/\n 2113,\n/**/\n 2112,\n/**/\n 2111,\n/**/\n 2110,\n/**/\n 2109,\n/**/\n 2108,\n/**/\n 2107,\n/**/\n 2106,\n/**/\n 2105,\n/**/\n 2104,\n/**/\n 2103,\n/**/\n 2102,\n/**/\n 2101,\n/**/\n 2100,\n/**/\n 2099,\n/**/\n 2098,\n/**/\n 2097,\n/**/\n 2096,\n/**/\n 2095,\n/**/\n 2094,\n/**/\n 2093,\n/**/\n 2092,\n/**/\n 2091,\n/**/\n 2090,\n/**/\n 2089,\n/**/\n 2088,\n/**/\n 2087,\n/**/\n 2086,\n/**/\n 2085,\n/**/\n 2084,\n/**/\n 2083,\n/**/\n 2082,\n/**/\n 2081,\n/**/\n 2080,\n/**/\n 2079,\n/**/\n 2078,\n/**/\n 2077,\n/**/\n 2076,\n/**/\n 2075,\n/**/\n 2074,\n/**/\n 2073,\n/**/\n 2072,\n/**/\n 2071,\n/**/\n 2070,\n/**/\n 2069,\n/**/\n 2068,\n/**/\n 2067,\n/**/\n 2066,\n/**/\n 2065,\n/**/\n 2064,\n/**/\n 2063,\n/**/\n 2062,\n/**/\n 2061,\n/**/\n 2060,\n/**/\n 2059,\n/**/\n 2058,\n/**/\n 2057,\n/**/\n 2056,\n/**/\n 2055,\n/**/\n 2054,\n/**/\n 2053,\n/**/\n 2052,\n/**/\n 2051,\n/**/\n 2050,\n/**/\n 2049,\n/**/\n 2048,\n/**/\n 2047,\n/**/\n 2046,\n/**/\n 2045,\n/**/\n 2044,\n/**/\n 2043,\n/**/\n 2042,\n/**/\n 2041,\n/**/\n 2040,\n/**/\n 2039,\n/**/\n 2038,\n/**/\n 2037,\n/**/\n 2036,\n/**/\n 2035,\n/**/\n 2034,\n/**/\n 2033,\n/**/\n 2032,\n/**/\n 2031,\n/**/\n 2030,\n/**/\n 2029,\n/**/\n 2028,\n/**/\n 2027,\n/**/\n 2026,\n/**/\n 2025,\n/**/\n 2024,\n/**/\n 2023,\n/**/\n 2022,\n/**/\n 2021,\n/**/\n 2020,\n/**/\n 2019,\n/**/\n 2018,\n/**/\n 2017,\n/**/\n 2016,\n/**/\n 2015,\n/**/\n 2014,\n/**/\n 2013,\n/**/\n 2012,\n/**/\n 2011,\n/**/\n 2010,\n/**/\n 2009,\n/**/\n 2008,\n/**/\n 2007,\n/**/\n 2006,\n/**/\n 2005,\n/**/\n 2004,\n/**/\n 2003,\n/**/\n 2002,\n/**/\n 2001,\n/**/\n 2000,\n/**/\n 1999,\n/**/\n 1998,\n/**/\n 1997,\n/**/\n 1996,\n/**/\n 1995,\n/**/\n 1994,\n/**/\n 1993,\n/**/\n 1992,\n/**/\n 1991,\n/**/\n 1990,\n/**/\n 1989,\n/**/\n 1988,\n/**/\n 1987,\n/**/\n 1986,\n/**/\n 1985,\n/**/\n 1984,\n/**/\n 1983,\n/**/\n 1982,\n/**/\n 1981,\n/**/\n 1980,\n/**/\n 1979,\n/**/\n 1978,\n/**/\n 1977,\n/**/\n 1976,\n/**/\n 1975,\n/**/\n 1974,\n/**/\n 1973,\n/**/\n 1972,\n/**/\n 1971,\n/**/\n 1970,\n/**/\n 1969,\n/**/\n 1968,\n/**/\n 1967,\n/**/\n 1966,\n/**/\n 1965,\n/**/\n 1964,\n/**/\n 1963,\n/**/\n 1962,\n/**/\n 1961,\n/**/\n 1960,\n/**/\n 1959,\n/**/\n 1958,\n/**/\n 1957,\n/**/\n 1956,\n/**/\n 1955,\n/**/\n 1954,\n/**/\n 1953,\n/**/\n 1952,\n/**/\n 1951,\n/**/\n 1950,\n/**/\n 1949,\n/**/\n 1948,\n/**/\n 1947,\n/**/\n 1946,\n/**/\n 1945,\n/**/\n 1944,\n/**/\n 1943,\n/**/\n 1942,\n/**/\n 1941,\n/**/\n 1940,\n/**/\n 1939,\n/**/\n 1938,\n/**/\n 1937,\n/**/\n 1936,\n/**/\n 1935,\n/**/\n 1934,\n/**/\n 1933,\n/**/\n 1932,\n/**/\n 1931,\n/**/\n 1930,\n/**/\n 1929,\n/**/\n 1928,\n/**/\n 1927,\n/**/\n 1926,\n/**/\n 1925,\n/**/\n 1924,\n/**/\n 1923,\n/**/\n 1922,\n/**/\n 1921,\n/**/\n 1920,\n/**/\n 1919,\n/**/\n 1918,\n/**/\n 1917,\n/**/\n 1916,\n/**/\n 1915,\n/**/\n 1914,\n/**/\n 1913,\n/**/\n 1912,\n/**/\n 1911,\n/**/\n 1910,\n/**/\n 1909,\n/**/\n 1908,\n/**/\n 1907,\n/**/\n 1906,\n/**/\n 1905,\n/**/\n 1904,\n/**/\n 1903,\n/**/\n 1902,\n/**/\n 1901,\n/**/\n 1900,\n/**/\n 1899,\n/**/\n 1898,\n/**/\n 1897,\n/**/\n 1896,\n/**/\n 1895,\n/**/\n 1894,\n/**/\n 1893,\n/**/\n 1892,\n/**/\n 1891,\n/**/\n 1890,\n/**/\n 1889,\n/**/\n 1888,\n/**/\n 1887,\n/**/\n 1886,\n/**/\n 1885,\n/**/\n 1884,\n/**/\n 1883,\n/**/\n 1882,\n/**/\n 1881,\n/**/\n 1880,\n/**/\n 1879,\n/**/\n 1878,\n/**/\n 1877,\n/**/\n 1876,\n/**/\n 1875,\n/**/\n 1874,\n/**/\n 1873,\n/**/\n 1872,\n/**/\n 1871,\n/**/\n 1870,\n/**/\n 1869,\n/**/\n 1868,\n/**/\n 1867,\n/**/\n 1866,\n/**/\n 1865,\n/**/\n 1864,\n/**/\n 1863,\n/**/\n 1862,\n/**/\n 1861,\n/**/\n 1860,\n/**/\n 1859,\n/**/\n 1858,\n/**/\n 1857,\n/**/\n 1856,\n/**/\n 1855,\n/**/\n 1854,\n/**/\n 1853,\n/**/\n 1852,\n/**/\n 1851,\n/**/\n 1850,\n/**/\n 1849,\n/**/\n 1848,\n/**/\n 1847,\n/**/\n 1846,\n/**/\n 1845,\n/**/\n 1844,\n/**/\n 1843,\n/**/\n 1842,\n/**/\n 1841,\n/**/\n 1840,\n/**/\n 1839,\n/**/\n 1838,\n/**/\n 1837,\n/**/\n 1836,\n/**/\n 1835,\n/**/\n 1834,\n/**/\n 1833,\n/**/\n 1832,\n/**/\n 1831,\n/**/\n 1830,\n/**/\n 1829,\n/**/\n 1828,\n/**/\n 1827,\n/**/\n 1826,\n/**/\n 1825,\n/**/\n 1824,\n/**/\n 1823,\n/**/\n 1822,\n/**/\n 1821,\n/**/\n 1820,\n/**/\n 1819,\n/**/\n 1818,\n/**/\n 1817,\n/**/\n 1816,\n/**/\n 1815,\n/**/\n 1814,\n/**/\n 1813,\n/**/\n 1812,\n/**/\n 1811,\n/**/\n 1810,\n/**/\n 1809,\n/**/\n 1808,\n/**/\n 1807,\n/**/\n 1806,\n/**/\n 1805,\n/**/\n 1804,\n/**/\n 1803,\n/**/\n 1802,\n/**/\n 1801,\n/**/\n 1800,\n/**/\n 1799,\n/**/\n 1798,\n/**/\n 1797,\n/**/\n 1796,\n/**/\n 1795,\n/**/\n 1794,\n/**/\n 1793,\n/**/\n 1792,\n/**/\n 1791,\n/**/\n 1790,\n/**/\n 1789,\n/**/\n 1788,\n/**/\n 1787,\n/**/\n 1786,\n/**/\n 1785,\n/**/\n 1784,\n/**/\n 1783,\n/**/\n 1782,\n/**/\n 1781,\n/**/\n 1780,\n/**/\n 1779,\n/**/\n 1778,\n/**/\n 1777,\n/**/\n 1776,\n/**/\n 1775,\n/**/\n 1774,\n/**/\n 1773,\n/**/\n 1772,\n/**/\n 1771,\n/**/\n 1770,\n/**/\n 1769,\n/**/\n 1768,\n/**/\n 1767,\n/**/\n 1766,\n/**/\n 1765,\n/**/\n 1764,\n/**/\n 1763,\n/**/\n 1762,\n/**/\n 1761,\n/**/\n 1760,\n/**/\n 1759,\n/**/\n 1758,\n/**/\n 1757,\n/**/\n 1756,\n/**/\n 1755,\n/**/\n 1754,\n/**/\n 1753,\n/**/\n 1752,\n/**/\n 1751,\n/**/\n 1750,\n/**/\n 1749,\n/**/\n 1748,\n/**/\n 1747,\n/**/\n 1746,\n/**/\n 1745,\n/**/\n 1744,\n/**/\n 1743,\n/**/\n 1742,\n/**/\n 1741,\n/**/\n 1740,\n/**/\n 1739,\n/**/\n 1738,\n/**/\n 1737,\n/**/\n 1736,\n/**/\n 1735,\n/**/\n 1734,\n/**/\n 1733,\n/**/\n 1732,\n/**/\n 1731,\n/**/\n 1730,\n/**/\n 1729,\n/**/\n 1728,\n/**/\n 1727,\n/**/\n 1726,\n/**/\n 1725,\n/**/\n 1724,\n/**/\n 1723,\n/**/\n 1722,\n/**/\n 1721,\n/**/\n 1720,\n/**/\n 1719,\n/**/\n 1718,\n/**/\n 1717,\n/**/\n 1716,\n/**/\n 1715,\n/**/\n 1714,\n/**/\n 1713,\n/**/\n 1712,\n/**/\n 1711,\n/**/\n 1710,\n/**/\n 1709,\n/**/\n 1708,\n/**/\n 1707,\n/**/\n 1706,\n/**/\n 1705,\n/**/\n 1704,\n/**/\n 1703,\n/**/\n 1702,\n/**/\n 1701,\n/**/\n 1700,\n/**/\n 1699,\n/**/\n 1698,\n/**/\n 1697,\n/**/\n 1696,\n/**/\n 1695,\n/**/\n 1694,\n/**/\n 1693,\n/**/\n 1692,\n/**/\n 1691,\n/**/\n 1690,\n/**/\n 1689,\n/**/\n 1688,\n/**/\n 1687,\n/**/\n 1686,\n/**/\n 1685,\n/**/\n 1684,\n/**/\n 1683,\n/**/\n 1682,\n/**/\n 1681,\n/**/\n 1680,\n/**/\n 1679,\n/**/\n 1678,\n/**/\n 1677,\n/**/\n 1676,\n/**/\n 1675,\n/**/\n 1674,\n/**/\n 1673,\n/**/\n 1672,\n/**/\n 1671,\n/**/\n 1670,\n/**/\n 1669,\n/**/\n 1668,\n/**/\n 1667,\n/**/\n 1666,\n/**/\n 1665,\n/**/\n 1664,\n/**/\n 1663,\n/**/\n 1662,\n/**/\n 1661,\n/**/\n 1660,\n/**/\n 1659,\n/**/\n 1658,\n/**/\n 1657,\n/**/\n 1656,\n/**/\n 1655,\n/**/\n 1654,\n/**/\n 1653,\n/**/\n 1652,\n/**/\n 1651,\n/**/\n 1650,\n/**/\n 1649,\n/**/\n 1648,\n/**/\n 1647,\n/**/\n 1646,\n/**/\n 1645,\n/**/\n 1644,\n/**/\n 1643,\n/**/\n 1642,\n/**/\n 1641,\n/**/\n 1640,\n/**/\n 1639,\n/**/\n 1638,\n/**/\n 1637,\n/**/\n 1636,\n/**/\n 1635,\n/**/\n 1634,\n/**/\n 1633,\n/**/\n 1632,\n/**/\n 1631,\n/**/\n 1630,\n/**/\n 1629,\n/**/\n 1628,\n/**/\n 1627,\n/**/\n 1626,\n/**/\n 1625,\n/**/\n 1624,\n/**/\n 1623,\n/**/\n 1622,\n/**/\n 1621,\n/**/\n 1620,\n/**/\n 1619,\n/**/\n 1618,\n/**/\n 1617,\n/**/\n 1616,\n/**/\n 1615,\n/**/\n 1614,\n/**/\n 1613,\n/**/\n 1612,\n/**/\n 1611,\n/**/\n 1610,\n/**/\n 1609,\n/**/\n 1608,\n/**/\n 1607,\n/**/\n 1606,\n/**/\n 1605,\n/**/\n 1604,\n/**/\n 1603,\n/**/\n 1602,\n/**/\n 1601,\n/**/\n 1600,\n/**/\n 1599,\n/**/\n 1598,\n/**/\n 1597,\n/**/\n 1596,\n/**/\n 1595,\n/**/\n 1594,\n/**/\n 1593,\n/**/\n 1592,\n/**/\n 1591,\n/**/\n 1590,\n/**/\n 1589,\n/**/\n 1588,\n/**/\n 1587,\n/**/\n 1586,\n/**/\n 1585,\n/**/\n 1584,\n/**/\n 1583,\n/**/\n 1582,\n/**/\n 1581,\n/**/\n 1580,\n/**/\n 1579,\n/**/\n 1578,\n/**/\n 1577,\n/**/\n 1576,\n/**/\n 1575,\n/**/\n 1574,\n/**/\n 1573,\n/**/\n 1572,\n/**/\n 1571,\n/**/\n 1570,\n/**/\n 1569,\n/**/\n 1568,\n/**/\n 1567,\n/**/\n 1566,\n/**/\n 1565,\n/**/\n 1564,\n/**/\n 1563,\n/**/\n 1562,\n/**/\n 1561,\n/**/\n 1560,\n/**/\n 1559,\n/**/\n 1558,\n/**/\n 1557,\n/**/\n 1556,\n/**/\n 1555,\n/**/\n 1554,\n/**/\n 1553,\n/**/\n 1552,\n/**/\n 1551,\n/**/\n 1550,\n/**/\n 1549,\n/**/\n 1548,\n/**/\n 1547,\n/**/\n 1546,\n/**/\n 1545,\n/**/\n 1544,\n/**/\n 1543,\n/**/\n 1542,\n/**/\n 1541,\n/**/\n 1540,\n/**/\n 1539,\n/**/\n 1538,\n/**/\n 1537,\n/**/\n 1536,\n/**/\n 1535,\n/**/\n 1534,\n/**/\n 1533,\n/**/\n 1532,\n/**/\n 1531,\n/**/\n 1530,\n/**/\n 1529,\n/**/\n 1528,\n/**/\n 1527,\n/**/\n 1526,\n/**/\n 1525,\n/**/\n 1524,\n/**/\n 1523,\n/**/\n 1522,\n/**/\n 1521,\n/**/\n 1520,\n/**/\n 1519,\n/**/\n 1518,\n/**/\n 1517,\n/**/\n 1516,\n/**/\n 1515,\n/**/\n 1514,\n/**/\n 1513,\n/**/\n 1512,\n/**/\n 1511,\n/**/\n 1510,\n/**/\n 1509,\n/**/\n 1508,\n/**/\n 1507,\n/**/\n 1506,\n/**/\n 1505,\n/**/\n 1504,\n/**/\n 1503,\n/**/\n 1502,\n/**/\n 1501,\n/**/\n 1500,\n/**/\n 1499,\n/**/\n 1498,\n/**/\n 1497,\n/**/\n 1496,\n/**/\n 1495,\n/**/\n 1494,\n/**/\n 1493,\n/**/\n 1492,\n/**/\n 1491,\n/**/\n 1490,\n/**/\n 1489,\n/**/\n 1488,\n/**/\n 1487,\n/**/\n 1486,\n/**/\n 1485,\n/**/\n 1484,\n/**/\n 1483,\n/**/\n 1482,\n/**/\n 1481,\n/**/\n 1480,\n/**/\n 1479,\n/**/\n 1478,\n/**/\n 1477,\n/**/\n 1476,\n/**/\n 1475,\n/**/\n 1474,\n/**/\n 1473,\n/**/\n 1472,\n/**/\n 1471,\n/**/\n 1470,\n/**/\n 1469,\n/**/\n 1468,\n/**/\n 1467,\n/**/\n 1466,\n/**/\n 1465,\n/**/\n 1464,\n/**/\n 1463,\n/**/\n 1462,\n/**/\n 1461,\n/**/\n 1460,\n/**/\n 1459,\n/**/\n 1458,\n/**/\n 1457,\n/**/\n 1456,\n/**/\n 1455,\n/**/\n 1454,\n/**/\n 1453,\n/**/\n 1452,\n/**/\n 1451,\n/**/\n 1450,\n/**/\n 1449,\n/**/\n 1448,\n/**/\n 1447,\n/**/\n 1446,\n/**/\n 1445,\n/**/\n 1444,\n/**/\n 1443,\n/**/\n 1442,\n/**/\n 1441,\n/**/\n 1440,\n/**/\n 1439,\n/**/\n 1438,\n/**/\n 1437,\n/**/\n 1436,\n/**/\n 1435,\n/**/\n 1434,\n/**/\n 1433,\n/**/\n 1432,\n/**/\n 1431,\n/**/\n 1430,\n/**/\n 1429,\n/**/\n 1428,\n/**/\n 1427,\n/**/\n 1426,\n/**/\n 1425,\n/**/\n 1424,\n/**/\n 1423,\n/**/\n 1422,\n/**/\n 1421,\n/**/\n 1420,\n/**/\n 1419,\n/**/\n 1418,\n/**/\n 1417,\n/**/\n 1416,\n/**/\n 1415,\n/**/\n 1414,\n/**/\n 1413,\n/**/\n 1412,\n/**/\n 1411,\n/**/\n 1410,\n/**/\n 1409,\n/**/\n 1408,\n/**/\n 1407,\n/**/\n 1406,\n/**/\n 1405,\n/**/\n 1404,\n/**/\n 1403,\n/**/\n 1402,\n/**/\n 1401,\n/**/\n 1400,\n/**/\n 1399,\n/**/\n 1398,\n/**/\n 1397,\n/**/\n 1396,\n/**/\n 1395,\n/**/\n 1394,\n/**/\n 1393,\n/**/\n 1392,\n/**/\n 1391,\n/**/\n 1390,\n/**/\n 1389,\n/**/\n 1388,\n/**/\n 1387,\n/**/\n 1386,\n/**/\n 1385,\n/**/\n 1384,\n/**/\n 1383,\n/**/\n 1382,\n/**/\n 1381,\n/**/\n 1380,\n/**/\n 1379,\n/**/\n 1378,\n/**/\n 1377,\n/**/\n 1376,\n/**/\n 1375,\n/**/\n 1374,\n/**/\n 1373,\n/**/\n 1372,\n/**/\n 1371,\n/**/\n 1370,\n/**/\n 1369,\n/**/\n 1368,\n/**/\n 1367,\n/**/\n 1366,\n/**/\n 1365,\n/**/\n 1364,\n/**/\n 1363,\n/**/\n 1362,\n/**/\n 1361,\n/**/\n 1360,\n/**/\n 1359,\n/**/\n 1358,\n/**/\n 1357,\n/**/\n 1356,\n/**/\n 1355,\n/**/\n 1354,\n/**/\n 1353,\n/**/\n 1352,\n/**/\n 1351,\n/**/\n 1350,\n/**/\n 1349,\n/**/\n 1348,\n/**/\n 1347,\n/**/\n 1346,\n/**/\n 1345,\n/**/\n 1344,\n/**/\n 1343,\n/**/\n 1342,\n/**/\n 1341,\n/**/\n 1340,\n/**/\n 1339,\n/**/\n 1338,\n/**/\n 1337,\n/**/\n 1336,\n/**/\n 1335,\n/**/\n 1334,\n/**/\n 1333,\n/**/\n 1332,\n/**/\n 1331,\n/**/\n 1330,\n/**/\n 1329,\n/**/\n 1328,\n/**/\n 1327,\n/**/\n 1326,\n/**/\n 1325,\n/**/\n 1324,\n/**/\n 1323,\n/**/\n 1322,\n/**/\n 1321,\n/**/\n 1320,\n/**/\n 1319,\n/**/\n 1318,\n/**/\n 1317,\n/**/\n 1316,\n/**/\n 1315,\n/**/\n 1314,\n/**/\n 1313,\n/**/\n 1312,\n/**/\n 1311,\n/**/\n 1310,\n/**/\n 1309,\n/**/\n 1308,\n/**/\n 1307,\n/**/\n 1306,\n/**/\n 1305,\n/**/\n 1304,\n/**/\n 1303,\n/**/\n 1302,\n/**/\n 1301,\n/**/\n 1300,\n/**/\n 1299,\n/**/\n 1298,\n/**/\n 1297,\n/**/\n 1296,\n/**/\n 1295,\n/**/\n 1294,\n/**/\n 1293,\n/**/\n 1292,\n/**/\n 1291,\n/**/\n 1290,\n/**/\n 1289,\n/**/\n 1288,\n/**/\n 1287,\n/**/\n 1286,\n/**/\n 1285,\n/**/\n 1284,\n/**/\n 1283,\n/**/\n 1282,\n/**/\n 1281,\n/**/\n 1280,\n/**/\n 1279,\n/**/\n 1278,\n/**/\n 1277,\n/**/\n 1276,\n/**/\n 1275,\n/**/\n 1274,\n/**/\n 1273,\n/**/\n 1272,\n/**/\n 1271,\n/**/\n 1270,\n/**/\n 1269,\n/**/\n 1268,\n/**/\n 1267,\n/**/\n 1266,\n/**/\n 1265,\n/**/\n 1264,\n/**/\n 1263,\n/**/\n 1262,\n/**/\n 1261,\n/**/\n 1260,\n/**/\n 1259,\n/**/\n 1258,\n/**/\n 1257,\n/**/\n 1256,\n/**/\n 1255,\n/**/\n 1254,\n/**/\n 1253,\n/**/\n 1252,\n/**/\n 1251,\n/**/\n 1250,\n/**/\n 1249,\n/**/\n 1248,\n/**/\n 1247,\n/**/\n 1246,\n/**/\n 1245,\n/**/\n 1244,\n/**/\n 1243,\n/**/\n 1242,\n/**/\n 1241,\n/**/\n 1240,\n/**/\n 1239,\n/**/\n 1238,\n/**/\n 1237,\n/**/\n 1236,\n/**/\n 1235,\n/**/\n 1234,\n/**/\n 1233,\n/**/\n 1232,\n/**/\n 1231,\n/**/\n 1230,\n/**/\n 1229,\n/**/\n 1228,\n/**/\n 1227,\n/**/\n 1226,\n/**/\n 1225,\n/**/\n 1224,\n/**/\n 1223,\n/**/\n 1222,\n/**/\n 1221,\n/**/\n 1220,\n/**/\n 1219,\n/**/\n 1218,\n/**/\n 1217,\n/**/\n 1216,\n/**/\n 1215,\n/**/\n 1214,\n/**/\n 1213,\n/**/\n 1212,\n/**/\n 1211,\n/**/\n 1210,\n/**/\n 1209,\n/**/\n 1208,\n/**/\n 1207,\n/**/\n 1206,\n/**/\n 1205,\n/**/\n 1204,\n/**/\n 1203,\n/**/\n 1202,\n/**/\n 1201,\n/**/\n 1200,\n/**/\n 1199,\n/**/\n 1198,\n/**/\n 1197,\n/**/\n 1196,\n/**/\n 1195,\n/**/\n 1194,\n/**/\n 1193,\n/**/\n 1192,\n/**/\n 1191,\n/**/\n 1190,\n/**/\n 1189,\n/**/\n 1188,\n/**/\n 1187,\n/**/\n 1186,\n/**/\n 1185,\n/**/\n 1184,\n/**/\n 1183,\n/**/\n 1182,\n/**/\n 1181,\n/**/\n 1180,\n/**/\n 1179,\n/**/\n 1178,\n/**/\n 1177,\n/**/\n 1176,\n/**/\n 1175,\n/**/\n 1174,\n/**/\n 1173,\n/**/\n 1172,\n/**/\n 1171,\n/**/\n 1170,\n/**/\n 1169,\n/**/\n 1168,\n/**/\n 1167,\n/**/\n 1166,\n/**/\n 1165,\n/**/\n 1164,\n/**/\n 1163,\n/**/\n 1162,\n/**/\n 1161,\n/**/\n 1160,\n/**/\n 1159,\n/**/\n 1158,\n/**/\n 1157,\n/**/\n 1156,\n/**/\n 1155,\n/**/\n 1154,\n/**/\n 1153,\n/**/\n 1152,\n/**/\n 1151,\n/**/\n 1150,\n/**/\n 1149,\n/**/\n 1148,\n/**/\n 1147,\n/**/\n 1146,\n/**/\n 1145,\n/**/\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 while (l < h)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\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 version8<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": [1491, 804, 736], "buggy_code_start_loc": [1278, 804, 736], "filenames": ["src/spell.c", "src/testdir/test_spell_utf8.vim", "src/version.c"], "fixing_code_end_loc": [1495, 820, 739], "fixing_code_start_loc": [1278, 805, 737], "message": "Use After Free in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "8B6CDC65-37D1-4A6A-B6C5-7B58DC5757ED", "versionEndExcluding": "8.2.5072", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "0146DEE5-EF72-48C3-9DDD-28EA3595BDD1", "versionEndExcluding": "11.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:apple:macos:*:*:*:*:*:*:*:*", "matchCriteriaId": "7B7BC361-3A04-4C88-A3AE-82B9993A73A0", "versionEndExcluding": "12.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "12.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Use After Free in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Un Uso de Memoria Previamente Liberada en el repositorio GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2042", "lastModified": "2023-05-03T12:15:40.820", "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": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:L/UI:R/S:C/C:H/I:H/A:L", "version": "3.0"}, "exploitabilityScore": 0.8, "impactScore": 6.0, "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-06-10T19:15:08.813", "references": [{"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/28"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/41"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/43"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2022/Oct/45"}, {"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/8628b4cd-4055-4059-aed4-64f7fdc10eba"}, {"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"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213443"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213444"}, {"source": "security@huntr.dev", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT213488"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-416"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-416"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/2813f38e021c6e6581c0c88fcf107e41788bc835"}, "type": "CWE-416"}
| 317
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"use LibreNMS\\Util\\Number;",
"$bill_id = $vars['bill_id'];",
"if (Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/actions.inc.php';\n}",
"if (bill_permitted($bill_id)) {\n $bill_data = dbFetchRow('SELECT * FROM bills WHERE bill_id = ?', [$bill_id]);",
" $bill_name = $bill_data['bill_name'];",
" $today = str_replace('-', '', dbFetchCell('SELECT CURDATE()'));\n $yesterday = str_replace('-', '', dbFetchCell('SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY)'));\n $tomorrow = str_replace('-', '', dbFetchCell('SELECT DATE_ADD(CURDATE(), INTERVAL 1 DAY)'));\n $last_month = str_replace('-', '', dbFetchCell('SELECT DATE_SUB(CURDATE(), INTERVAL 1 MONTH)'));",
" $rightnow = $today . date('His');\n $before = $yesterday . date('His');\n $lastmonth = $last_month . date('His');",
" $bill_name = $bill_data['bill_name'];\n $dayofmonth = $bill_data['bill_day'];",
" $day_data = getDates($dayofmonth);",
" $datefrom = $day_data['0'];\n $dateto = $day_data['1'];\n $lastfrom = $day_data['2'];\n $lastto = $day_data['3'];",
" $rate_95th = $bill_data['rate_95th'];\n $dir_95th = $bill_data['dir_95th'];\n $total_data = $bill_data['total_data'];\n $rate_average = $bill_data['rate_average'];",
" if ($rate_95th > $paid_kb) {\n $over = ($rate_95th - $paid_kb);\n $bill_text = $over . 'Kbit excess.';\n $bill_color = '#cc0000';\n } else {\n $under = ($paid_kb - $rate_95th);\n $bill_text = $under . 'Kbit headroom.';\n $bill_color = '#0000cc';\n }",
" $fromtext = dbFetchCell(\"SELECT DATE_FORMAT($datefrom, '\" . \\LibreNMS\\Config::get('dateformat.mysql.date') . \"')\");\n $totext = dbFetchCell(\"SELECT DATE_FORMAT($dateto, '\" . \\LibreNMS\\Config::get('dateformat.mysql.date') . \"')\");\n $unixfrom = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$datefrom')\");\n $unixto = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$dateto')\");",
" $unix_prev_from = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$lastfrom')\");\n $unix_prev_to = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$lastto')\");\n // Speeds up loading for other included pages by setting it before progessing of mysql data!\n $ports = dbFetchRows(\n 'SELECT * FROM `bill_ports` AS B, `ports` AS P, `devices` AS D\n WHERE B.bill_id = ? AND P.port_id = B.port_id\n AND D.device_id = P.device_id',\n [$bill_id]\n );",
" if (! $vars['view']) {\n $vars['view'] = 'quick';\n }",
" function print_port_list($ports)\n {\n echo '<div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 class=\"panel-title\">Billed Ports</h3>\n </div>\n <div class=\"list-group\">';",
" // Collected Earlier\n foreach ($ports as $port) {\n $port = cleanPort($port);\n $portalias = (empty($port['ifAlias']) ? '' : ' - ' . $port['ifAlias'] . '');",
" echo '<div class=\"list-group-item\">';\n echo generate_port_link($port, $port['ifName'] . $portalias) . ' on ' . generate_device_link($port);\n echo '</div>';\n }",
" echo '</div></div>';\n }//end print_port_list?>\n",
" <h2><?php echo \"Bill: ${bill_data['bill_name']}\"; ?></h2>",
"\n <?php\n print_optionbar_start();\n echo '<strong>Bill</strong> » ';\n $menu_options = [\n 'quick' => 'Quick Graphs',\n 'accurate' => 'Accurate Graphs',\n 'transfer' => 'Transfer Graphs',\n 'history' => 'Historical Graphs',\n ];\n if (Auth::user()->hasGlobalAdmin()) {\n $menu_options['edit'] = 'Edit';\n $menu_options['delete'] = 'Delete';\n $menu_options['reset'] = 'Reset';\n }\n $sep = '';\n foreach ($menu_options as $option => $text) {\n echo $sep;\n if ($vars['view'] == $option) {\n echo \"<span class='pagemenu-selected'>\";\n }",
" echo generate_link($text, $vars, ['view' => $option]);\n if ($vars['view'] == $option) {\n echo '</span>';\n }",
" $sep = ' | ';\n }",
" echo '<div style=\"font-weight: bold; float: right;\"><a href=\"' . \\LibreNMS\\Util\\Url::generate(['page' => 'bills']) . '/\"><i class=\"fa fa-arrow-left fa-lg icon-theme\" aria-hidden=\"true\"></i> Back to Bills</a></div>';",
" print_optionbar_end();",
" if ($vars['view'] == 'edit' && Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/edit.inc.php';\n } elseif ($vars['view'] == 'delete' && Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/delete.inc.php';\n } elseif ($vars['view'] == 'reset' && Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/reset.inc.php';\n } elseif ($vars['view'] == 'history') {\n include 'includes/html/pages/bill/history.inc.php';\n } elseif ($vars['view'] == 'transfer') {\n include 'includes/html/pages/bill/transfer.inc.php';\n } elseif ($vars['view'] == 'quick' || $vars['view'] == 'accurate') {\n ?>",
" <?php if ($bill_data['bill_type'] == 'quota') { ?>\n <h3>Quota Bill</h3>\n <?php } elseif ($bill_data['bill_type'] == 'cdr') { ?>\n <h3>\n CDR / 95th Bill\n </h3>\n <?php } ?>\n<strong>Billing Period from <?php echo $fromtext ?> to <?php echo $totext ?></strong>\n<br /><br />",
"<div class=\"row\">\n<div class=\"col-lg-6 col-lg-push-6\">\n <?php print_port_list($ports) ?>\n</div>\n<div class=\"col-lg-6 col-lg-pull-6\">\n<div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 class=\"panel-title\">\n Bill Summary\n </h3>\n </div>\n <table class=\"table\">\n <tr>\n <?php if ($bill_data['bill_type'] == 'quota') {\n // The Customer is billed based on a pre-paid quota with overage in xB\n $percent = Number::calculatePercent($total_data, $bill_data['bill_quota']);\n $unit = 'MB';\n $total_data = round($total_data, 2);\n $background = \\LibreNMS\\Util\\Color::percentage($percent, null);\n $type = '&ave=yes'; ?>\n <td>\n <?php echo format_bytes_billing($total_data) ?> of <?php echo format_bytes_billing($bill_data['bill_quota']) . ' (' . $percent . '%)' ?>\n - Average rate <?php echo Number::formatSi($rate_average, 2, 3, 'bps') ?>\n </td>\n <td style=\"width: 210px;\"><?php echo print_percentage_bar(200, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']) ?></td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <?php\n echo 'Predicted usage: ' . format_bytes_billing(getPredictedUsage($bill_data['bill_day'], $bill_data['total_data'])); ?>\n </td>\n <?php\n } elseif ($bill_data['bill_type'] == 'cdr') {\n // The customer is billed based on a CDR with 95th%ile overage\n $unit = 'kbps';\n $cdr = $bill_data['bill_cdr'];\n $rate_95th = round($rate_95th, 2);\n $percent = Number::calculatePercent($rate_95th, $cdr);\n $background = \\LibreNMS\\Util\\Color::percentage($percent, null);\n $type = '&95th=yes'; ?>\n <td>\n <?php echo Number::formatSi($rate_95th, 2, 3, '') . 'bps' ?> of <?php echo Number::formatSi($cdr, 2, 3, '') . 'bps (' . $percent . '%)' ?> (95th%ile)\n </td>\n <td style=\"width: 210px;\">\n <?php echo print_percentage_bar(200, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']) ?>\n </td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <?php\n echo 'Predicted usage: ' . Number::formatSi(getPredictedUsage($bill_data['bill_day'], $bill_data['rate_95th']), 2, 3, '') . 'bps'; ?>\n </td>",
" <?php\n }//end if?>\n </tr>\n </table>\n</div>\n</div>\n</div>",
" <?php",
" $lastmonth = dbFetchCell('SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MONTH))');\n $yesterday = dbFetchCell('SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))');\n $rightnow = date('U');",
" if ($vars['view'] == 'accurate') {\n $bi = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . htmlspecialchars($_GET['bill_code']);\n $bi .= '&from=' . $unixfrom . '&to=' . $unixto;\n $bi .= '&x=1190&y=250';\n $bi .= \"$type'>\";",
" $li = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . $_GET['bill_code'];\n $li .= '&from=' . $unix_prev_from . '&to=' . $unix_prev_to;\n $li .= '&x=1190&y=250';\n $li .= \"$type'>\";",
" $di = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . htmlspecialchars($_GET['bill_code']);\n $di .= '&from=' . \\LibreNMS\\Config::get('time.day') . '&to=' . \\LibreNMS\\Config::get('time.now');\n $di .= '&x=1190&y=250';\n $di .= \"$type'>\";",
" $mi = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . htmlspecialchars($_GET['bill_code']);\n $mi .= '&from=' . $lastmonth . '&to=' . $rightnow;\n $mi .= '&x=1190&y=250';\n $mi .= \"$type'>\";\n } else {\n $bi = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $bi .= '&from=' . $unixfrom . '&to=' . $unixto;\n $bi .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";",
" $li = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $li .= '&from=' . $unix_prev_from . '&to=' . $unix_prev_to;\n $li .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";",
" $di = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $di .= '&from=' . \\LibreNMS\\Config::get('time.day') . '&to=' . \\LibreNMS\\Config::get('time.now');\n $di .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";",
" $mi = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $mi .= '&from=' . $lastmonth . '&to=' . $rightnow;\n $mi .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";\n }//end if",
" ?>\n<div class=\"panel panel-default\">\n<div class=\"panel-heading\">\n <h3 class=\"panel-title\">Billing View</h3>\n</div>\n <?php echo $bi ?>\n</div>",
"<div class=\"panel panel-default\">\n<div class=\"panel-heading\">\n <h3 class=\"panel-title\">24 Hour View</h3>\n</div>\n <?php echo $di ?>\n</div>",
"<div class=\"panel panel-default\">\n<div class=\"panel-heading\">\n <h3 class=\"panel-title\">Monthly View</h3>\n</div>\n <?php echo $mi ?>\n</div>\n <?php\n } //end if\n} else {\n include 'includes/html/error-no-perm.inc.php';\n}//end if\n?>"
] |
[
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
] |
PreciseBugs
|
{"buggy_code_end_loc": [91, 107, 146], "buggy_code_start_loc": [90, 5, 97], "filenames": ["includes/html/pages/bill.inc.php", "includes/html/pages/bill/addoreditbill.inc.php", "includes/html/table/bills.inc.php"], "fixing_code_end_loc": [91, 107, 146], "fixing_code_start_loc": [90, 5, 97], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:librenms:librenms:*:*:*:*:*:*:*:*", "matchCriteriaId": "99D1C2AF-9BBB-4F7D-9FC3-4A645F7C284D", "versionEndExcluding": "22.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0."}], "evaluatorComment": null, "id": "CVE-2022-3562", "lastModified": "2022-11-21T13:19:19.830", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "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": "2022-11-20T05:15:11.810", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, {"source": "security@huntr.dev", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://huntr.dev/bounties/bb9f76db-1314-44ae-9ccc-2b69679aa657"}], "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/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, "type": "CWE-79"}
| 318
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"use LibreNMS\\Util\\Number;",
"$bill_id = $vars['bill_id'];",
"if (Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/actions.inc.php';\n}",
"if (bill_permitted($bill_id)) {\n $bill_data = dbFetchRow('SELECT * FROM bills WHERE bill_id = ?', [$bill_id]);",
" $bill_name = $bill_data['bill_name'];",
" $today = str_replace('-', '', dbFetchCell('SELECT CURDATE()'));\n $yesterday = str_replace('-', '', dbFetchCell('SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY)'));\n $tomorrow = str_replace('-', '', dbFetchCell('SELECT DATE_ADD(CURDATE(), INTERVAL 1 DAY)'));\n $last_month = str_replace('-', '', dbFetchCell('SELECT DATE_SUB(CURDATE(), INTERVAL 1 MONTH)'));",
" $rightnow = $today . date('His');\n $before = $yesterday . date('His');\n $lastmonth = $last_month . date('His');",
" $bill_name = $bill_data['bill_name'];\n $dayofmonth = $bill_data['bill_day'];",
" $day_data = getDates($dayofmonth);",
" $datefrom = $day_data['0'];\n $dateto = $day_data['1'];\n $lastfrom = $day_data['2'];\n $lastto = $day_data['3'];",
" $rate_95th = $bill_data['rate_95th'];\n $dir_95th = $bill_data['dir_95th'];\n $total_data = $bill_data['total_data'];\n $rate_average = $bill_data['rate_average'];",
" if ($rate_95th > $paid_kb) {\n $over = ($rate_95th - $paid_kb);\n $bill_text = $over . 'Kbit excess.';\n $bill_color = '#cc0000';\n } else {\n $under = ($paid_kb - $rate_95th);\n $bill_text = $under . 'Kbit headroom.';\n $bill_color = '#0000cc';\n }",
" $fromtext = dbFetchCell(\"SELECT DATE_FORMAT($datefrom, '\" . \\LibreNMS\\Config::get('dateformat.mysql.date') . \"')\");\n $totext = dbFetchCell(\"SELECT DATE_FORMAT($dateto, '\" . \\LibreNMS\\Config::get('dateformat.mysql.date') . \"')\");\n $unixfrom = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$datefrom')\");\n $unixto = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$dateto')\");",
" $unix_prev_from = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$lastfrom')\");\n $unix_prev_to = dbFetchCell(\"SELECT UNIX_TIMESTAMP('$lastto')\");\n // Speeds up loading for other included pages by setting it before progessing of mysql data!\n $ports = dbFetchRows(\n 'SELECT * FROM `bill_ports` AS B, `ports` AS P, `devices` AS D\n WHERE B.bill_id = ? AND P.port_id = B.port_id\n AND D.device_id = P.device_id',\n [$bill_id]\n );",
" if (! $vars['view']) {\n $vars['view'] = 'quick';\n }",
" function print_port_list($ports)\n {\n echo '<div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 class=\"panel-title\">Billed Ports</h3>\n </div>\n <div class=\"list-group\">';",
" // Collected Earlier\n foreach ($ports as $port) {\n $port = cleanPort($port);\n $portalias = (empty($port['ifAlias']) ? '' : ' - ' . $port['ifAlias'] . '');",
" echo '<div class=\"list-group-item\">';\n echo generate_port_link($port, $port['ifName'] . $portalias) . ' on ' . generate_device_link($port);\n echo '</div>';\n }",
" echo '</div></div>';\n }//end print_port_list?>\n",
" <h2>Bill: <?php echo htmlentities($bill_data['bill_name']); ?></h2>",
"\n <?php\n print_optionbar_start();\n echo '<strong>Bill</strong> » ';\n $menu_options = [\n 'quick' => 'Quick Graphs',\n 'accurate' => 'Accurate Graphs',\n 'transfer' => 'Transfer Graphs',\n 'history' => 'Historical Graphs',\n ];\n if (Auth::user()->hasGlobalAdmin()) {\n $menu_options['edit'] = 'Edit';\n $menu_options['delete'] = 'Delete';\n $menu_options['reset'] = 'Reset';\n }\n $sep = '';\n foreach ($menu_options as $option => $text) {\n echo $sep;\n if ($vars['view'] == $option) {\n echo \"<span class='pagemenu-selected'>\";\n }",
" echo generate_link($text, $vars, ['view' => $option]);\n if ($vars['view'] == $option) {\n echo '</span>';\n }",
" $sep = ' | ';\n }",
" echo '<div style=\"font-weight: bold; float: right;\"><a href=\"' . \\LibreNMS\\Util\\Url::generate(['page' => 'bills']) . '/\"><i class=\"fa fa-arrow-left fa-lg icon-theme\" aria-hidden=\"true\"></i> Back to Bills</a></div>';",
" print_optionbar_end();",
" if ($vars['view'] == 'edit' && Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/edit.inc.php';\n } elseif ($vars['view'] == 'delete' && Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/delete.inc.php';\n } elseif ($vars['view'] == 'reset' && Auth::user()->hasGlobalAdmin()) {\n include 'includes/html/pages/bill/reset.inc.php';\n } elseif ($vars['view'] == 'history') {\n include 'includes/html/pages/bill/history.inc.php';\n } elseif ($vars['view'] == 'transfer') {\n include 'includes/html/pages/bill/transfer.inc.php';\n } elseif ($vars['view'] == 'quick' || $vars['view'] == 'accurate') {\n ?>",
" <?php if ($bill_data['bill_type'] == 'quota') { ?>\n <h3>Quota Bill</h3>\n <?php } elseif ($bill_data['bill_type'] == 'cdr') { ?>\n <h3>\n CDR / 95th Bill\n </h3>\n <?php } ?>\n<strong>Billing Period from <?php echo $fromtext ?> to <?php echo $totext ?></strong>\n<br /><br />",
"<div class=\"row\">\n<div class=\"col-lg-6 col-lg-push-6\">\n <?php print_port_list($ports) ?>\n</div>\n<div class=\"col-lg-6 col-lg-pull-6\">\n<div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 class=\"panel-title\">\n Bill Summary\n </h3>\n </div>\n <table class=\"table\">\n <tr>\n <?php if ($bill_data['bill_type'] == 'quota') {\n // The Customer is billed based on a pre-paid quota with overage in xB\n $percent = Number::calculatePercent($total_data, $bill_data['bill_quota']);\n $unit = 'MB';\n $total_data = round($total_data, 2);\n $background = \\LibreNMS\\Util\\Color::percentage($percent, null);\n $type = '&ave=yes'; ?>\n <td>\n <?php echo format_bytes_billing($total_data) ?> of <?php echo format_bytes_billing($bill_data['bill_quota']) . ' (' . $percent . '%)' ?>\n - Average rate <?php echo Number::formatSi($rate_average, 2, 3, 'bps') ?>\n </td>\n <td style=\"width: 210px;\"><?php echo print_percentage_bar(200, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']) ?></td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <?php\n echo 'Predicted usage: ' . format_bytes_billing(getPredictedUsage($bill_data['bill_day'], $bill_data['total_data'])); ?>\n </td>\n <?php\n } elseif ($bill_data['bill_type'] == 'cdr') {\n // The customer is billed based on a CDR with 95th%ile overage\n $unit = 'kbps';\n $cdr = $bill_data['bill_cdr'];\n $rate_95th = round($rate_95th, 2);\n $percent = Number::calculatePercent($rate_95th, $cdr);\n $background = \\LibreNMS\\Util\\Color::percentage($percent, null);\n $type = '&95th=yes'; ?>\n <td>\n <?php echo Number::formatSi($rate_95th, 2, 3, '') . 'bps' ?> of <?php echo Number::formatSi($cdr, 2, 3, '') . 'bps (' . $percent . '%)' ?> (95th%ile)\n </td>\n <td style=\"width: 210px;\">\n <?php echo print_percentage_bar(200, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']) ?>\n </td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <?php\n echo 'Predicted usage: ' . Number::formatSi(getPredictedUsage($bill_data['bill_day'], $bill_data['rate_95th']), 2, 3, '') . 'bps'; ?>\n </td>",
" <?php\n }//end if?>\n </tr>\n </table>\n</div>\n</div>\n</div>",
" <?php",
" $lastmonth = dbFetchCell('SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MONTH))');\n $yesterday = dbFetchCell('SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))');\n $rightnow = date('U');",
" if ($vars['view'] == 'accurate') {\n $bi = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . htmlspecialchars($_GET['bill_code']);\n $bi .= '&from=' . $unixfrom . '&to=' . $unixto;\n $bi .= '&x=1190&y=250';\n $bi .= \"$type'>\";",
" $li = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . $_GET['bill_code'];\n $li .= '&from=' . $unix_prev_from . '&to=' . $unix_prev_to;\n $li .= '&x=1190&y=250';\n $li .= \"$type'>\";",
" $di = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . htmlspecialchars($_GET['bill_code']);\n $di .= '&from=' . \\LibreNMS\\Config::get('time.day') . '&to=' . \\LibreNMS\\Config::get('time.now');\n $di .= '&x=1190&y=250';\n $di .= \"$type'>\";",
" $mi = \"<img src='billing-graph.php?bill_id=\" . $bill_id . '&bill_code=' . htmlspecialchars($_GET['bill_code']);\n $mi .= '&from=' . $lastmonth . '&to=' . $rightnow;\n $mi .= '&x=1190&y=250';\n $mi .= \"$type'>\";\n } else {\n $bi = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $bi .= '&from=' . $unixfrom . '&to=' . $unixto;\n $bi .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";",
" $li = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $li .= '&from=' . $unix_prev_from . '&to=' . $unix_prev_to;\n $li .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";",
" $di = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $di .= '&from=' . \\LibreNMS\\Config::get('time.day') . '&to=' . \\LibreNMS\\Config::get('time.now');\n $di .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";",
" $mi = \"<img src='graph.php?type=bill_bits&id=\" . $bill_id;\n $mi .= '&from=' . $lastmonth . '&to=' . $rightnow;\n $mi .= '&width=1000&height=200&total=1&dir=' . $dir_95th . \"'>\";\n }//end if",
" ?>\n<div class=\"panel panel-default\">\n<div class=\"panel-heading\">\n <h3 class=\"panel-title\">Billing View</h3>\n</div>\n <?php echo $bi ?>\n</div>",
"<div class=\"panel panel-default\">\n<div class=\"panel-heading\">\n <h3 class=\"panel-title\">24 Hour View</h3>\n</div>\n <?php echo $di ?>\n</div>",
"<div class=\"panel panel-default\">\n<div class=\"panel-heading\">\n <h3 class=\"panel-title\">Monthly View</h3>\n</div>\n <?php echo $mi ?>\n</div>\n <?php\n } //end if\n} else {\n include 'includes/html/error-no-perm.inc.php';\n}//end if\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [91, 107, 146], "buggy_code_start_loc": [90, 5, 97], "filenames": ["includes/html/pages/bill.inc.php", "includes/html/pages/bill/addoreditbill.inc.php", "includes/html/table/bills.inc.php"], "fixing_code_end_loc": [91, 107, 146], "fixing_code_start_loc": [90, 5, 97], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:librenms:librenms:*:*:*:*:*:*:*:*", "matchCriteriaId": "99D1C2AF-9BBB-4F7D-9FC3-4A645F7C284D", "versionEndExcluding": "22.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0."}], "evaluatorComment": null, "id": "CVE-2022-3562", "lastModified": "2022-11-21T13:19:19.830", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "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": "2022-11-20T05:15:11.810", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, {"source": "security@huntr.dev", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://huntr.dev/bounties/bb9f76db-1314-44ae-9ccc-2b69679aa657"}], "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/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, "type": "CWE-79"}
| 318
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<h4>Bill Information</h4>\n<div class=\"form-group\">\n <label for=\"bill_name\" class=\"col-sm-4 control-label\">Description</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"text\" id=\"bill_name\" name=\"bill_name\" value=\"<?php echo $bill_data['bill_name']; ?>\">",
" </div>\n</div>\n<div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_type\">Billing Type</label>\n <div class=\"col-sm-8\">\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"bill_type\" id=\"bill_type_cdr\" value=\"cdr\"\n <?php\n if ($bill_data['bill_type'] == 'cdr') {\n echo 'checked';\n }\n ?> onchange=\"javascript: billType();\" /> CDR 95th\n </label>\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"bill_type\" id=\"bill_type_quota\" value=\"quota\"\n <?php\n if ($bill_data['bill_type'] == 'quota') {\n echo 'checked';\n }\n ?> onchange=\"javascript: billType();\" /> Quota\n </label>\n </div>\n</div>\n<div class=\"form-group\">\n <div id=\"cdrDiv\">\n <label class=\"col-sm-4 control-label\" for=\"bill_cdr\">CDR</label>\n <div class=\"col-sm-3\">\n <input class=\"form-control input-sm\" type=\"text\" name=\"bill_cdr\" value=\"<?php echo $cdr['data'] ?>\">\n </div>\n <div class=\"col-sm-5\">\n <select name=\"bill_cdr_type\" class=\"form-control input-sm\">\n <option <?php echo $cdr['select_kbps'] ?> value=\"Kbps\">Kilobits per second (Kbps)</option>\n <option <?php echo $cdr['select_mbps'] ?> value=\"Mbps\">Megabits per second (Mbps)</option>\n <option <?php echo $cdr['select_gbps'] ?> value=\"Gbps\">Gigabits per second (Gbps)</option>\n </select>\n </div>\n <label class=\"col-sm-4 control-label\" for=\"dir_95th\">95th Calculation</label>\n <div class=\"col-sm-8\">\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"dir_95th\" id=\"dir_95th_inout\" value=\"in\"\n <?php\n if ($bill_data['dir_95th'] == 'in' || $bill_data['dir_95th'] == 'out') {\n echo 'checked';\n }\n ?> /> Max In/Out\n </label>\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"dir_95th\" id=\"dir_95th_agg\" value=\"agg\"\n <?php\n if ($bill_data['dir_95th'] == 'agg') {\n echo 'checked';\n }\n ?> /> Aggregate\n </label>\n </div>\n </div>\n <div id=\"quotaDiv\">\n <label class=\"col-sm-4 control-label\" for=\"bill_quota\">Quota</label>\n <div class=\"col-sm-3\">\n <input class=\"form-control input-sm\" type=\"text\" name=\"bill_quota\" value=\"<?php echo $quota['data'] ?>\">\n </div>\n <div class=\"col-sm-5\">\n <select name=\"bill_quota_type\" class=\"form-control input-sm\">\n <option <?php echo $quota['select_mb'] ?> value=\"MB\">Megabytes (MB)</option>\n <option <?php echo $quota['select_gb'] ?> value=\"GB\">Gigabytes (GB)</option>\n <option <?php echo $quota['select_tb'] ?> value=\"TB\">Terabytes (TB)</option>\n </select>\n </div>\n </div>\n</div>\n<div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_day\">Billing Day</label>\n <div class=\"col-sm-2\">\n <select name=\"bill_day\" class=\"form-control input-sm\">\n <?php\n for ($x = 1; $x < 32; $x++) {\n $sel = $bill_data['bill_day'] == $x ? 'selected ' : '';\n echo \"<option $sel value='$x'>$x</option>\\n\";\n }\n ?>\n </select>\n </div>\n</div>\n<fieldset>\n <h4>Optional Information</h4>\n <div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_custid\">Customer Reference</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"text\" name=\"bill_custid\" value=\"<?php echo $bill_data['bill_custid'] ?>\">",
" </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_ref\">Billing Reference</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"text\" name=\"bill_ref\" value=\"<?php echo $bill_data['bill_ref']; ?>\">",
" </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_notes\">Notes</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"textarea\" name=\"bill_notes\" value=\"<?php echo $bill_data['bill_notes']; ?>\">",
" </div>\n </div>\n</fieldset>",
"<script type=\"text/javascript\">\nfunction billType() {\n var selected = $('input[name=bill_type]:checked').val();",
" $('#cdrDiv').toggle(selected === 'cdr');\n $('#quotaDiv').toggle(selected === 'quota');\n}\nbillType();\n</script>"
] |
[
1,
0,
1,
0,
1,
0,
1,
0,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [91, 107, 146], "buggy_code_start_loc": [90, 5, 97], "filenames": ["includes/html/pages/bill.inc.php", "includes/html/pages/bill/addoreditbill.inc.php", "includes/html/table/bills.inc.php"], "fixing_code_end_loc": [91, 107, 146], "fixing_code_start_loc": [90, 5, 97], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:librenms:librenms:*:*:*:*:*:*:*:*", "matchCriteriaId": "99D1C2AF-9BBB-4F7D-9FC3-4A645F7C284D", "versionEndExcluding": "22.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0."}], "evaluatorComment": null, "id": "CVE-2022-3562", "lastModified": "2022-11-21T13:19:19.830", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "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": "2022-11-20T05:15:11.810", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, {"source": "security@huntr.dev", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://huntr.dev/bounties/bb9f76db-1314-44ae-9ccc-2b69679aa657"}], "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/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, "type": "CWE-79"}
| 318
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<h4>Bill Information</h4>\n<div class=\"form-group\">\n <label for=\"bill_name\" class=\"col-sm-4 control-label\">Description</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"text\" id=\"bill_name\" name=\"bill_name\" value=\"<?php echo htmlentities($bill_data['bill_name']); ?>\">",
" </div>\n</div>\n<div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_type\">Billing Type</label>\n <div class=\"col-sm-8\">\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"bill_type\" id=\"bill_type_cdr\" value=\"cdr\"\n <?php\n if ($bill_data['bill_type'] == 'cdr') {\n echo 'checked';\n }\n ?> onchange=\"javascript: billType();\" /> CDR 95th\n </label>\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"bill_type\" id=\"bill_type_quota\" value=\"quota\"\n <?php\n if ($bill_data['bill_type'] == 'quota') {\n echo 'checked';\n }\n ?> onchange=\"javascript: billType();\" /> Quota\n </label>\n </div>\n</div>\n<div class=\"form-group\">\n <div id=\"cdrDiv\">\n <label class=\"col-sm-4 control-label\" for=\"bill_cdr\">CDR</label>\n <div class=\"col-sm-3\">\n <input class=\"form-control input-sm\" type=\"text\" name=\"bill_cdr\" value=\"<?php echo $cdr['data'] ?>\">\n </div>\n <div class=\"col-sm-5\">\n <select name=\"bill_cdr_type\" class=\"form-control input-sm\">\n <option <?php echo $cdr['select_kbps'] ?> value=\"Kbps\">Kilobits per second (Kbps)</option>\n <option <?php echo $cdr['select_mbps'] ?> value=\"Mbps\">Megabits per second (Mbps)</option>\n <option <?php echo $cdr['select_gbps'] ?> value=\"Gbps\">Gigabits per second (Gbps)</option>\n </select>\n </div>\n <label class=\"col-sm-4 control-label\" for=\"dir_95th\">95th Calculation</label>\n <div class=\"col-sm-8\">\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"dir_95th\" id=\"dir_95th_inout\" value=\"in\"\n <?php\n if ($bill_data['dir_95th'] == 'in' || $bill_data['dir_95th'] == 'out') {\n echo 'checked';\n }\n ?> /> Max In/Out\n </label>\n <label class=\"radio-inline\">\n <input type=\"radio\" name=\"dir_95th\" id=\"dir_95th_agg\" value=\"agg\"\n <?php\n if ($bill_data['dir_95th'] == 'agg') {\n echo 'checked';\n }\n ?> /> Aggregate\n </label>\n </div>\n </div>\n <div id=\"quotaDiv\">\n <label class=\"col-sm-4 control-label\" for=\"bill_quota\">Quota</label>\n <div class=\"col-sm-3\">\n <input class=\"form-control input-sm\" type=\"text\" name=\"bill_quota\" value=\"<?php echo $quota['data'] ?>\">\n </div>\n <div class=\"col-sm-5\">\n <select name=\"bill_quota_type\" class=\"form-control input-sm\">\n <option <?php echo $quota['select_mb'] ?> value=\"MB\">Megabytes (MB)</option>\n <option <?php echo $quota['select_gb'] ?> value=\"GB\">Gigabytes (GB)</option>\n <option <?php echo $quota['select_tb'] ?> value=\"TB\">Terabytes (TB)</option>\n </select>\n </div>\n </div>\n</div>\n<div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_day\">Billing Day</label>\n <div class=\"col-sm-2\">\n <select name=\"bill_day\" class=\"form-control input-sm\">\n <?php\n for ($x = 1; $x < 32; $x++) {\n $sel = $bill_data['bill_day'] == $x ? 'selected ' : '';\n echo \"<option $sel value='$x'>$x</option>\\n\";\n }\n ?>\n </select>\n </div>\n</div>\n<fieldset>\n <h4>Optional Information</h4>\n <div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_custid\">Customer Reference</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"text\" name=\"bill_custid\" value=\"<?php echo htmlentities($bill_data['bill_custid']); ?>\">",
" </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_ref\">Billing Reference</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"text\" name=\"bill_ref\" value=\"<?php echo htmlentities($bill_data['bill_ref']); ?>\">",
" </div>\n </div>\n <div class=\"form-group\">\n <label class=\"col-sm-4 control-label\" for=\"bill_notes\">Notes</label>\n <div class=\"col-sm-8\">",
" <input class=\"form-control input-sm\" type=\"textarea\" name=\"bill_notes\" value=\"<?php echo htmlentities($bill_data['bill_notes']); ?>\">",
" </div>\n </div>\n</fieldset>",
"<script type=\"text/javascript\">\nfunction billType() {\n var selected = $('input[name=bill_type]:checked').val();",
" $('#cdrDiv').toggle(selected === 'cdr');\n $('#quotaDiv').toggle(selected === 'quota');\n}\nbillType();\n</script>"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [91, 107, 146], "buggy_code_start_loc": [90, 5, 97], "filenames": ["includes/html/pages/bill.inc.php", "includes/html/pages/bill/addoreditbill.inc.php", "includes/html/table/bills.inc.php"], "fixing_code_end_loc": [91, 107, 146], "fixing_code_start_loc": [90, 5, 97], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:librenms:librenms:*:*:*:*:*:*:*:*", "matchCriteriaId": "99D1C2AF-9BBB-4F7D-9FC3-4A645F7C284D", "versionEndExcluding": "22.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0."}], "evaluatorComment": null, "id": "CVE-2022-3562", "lastModified": "2022-11-21T13:19:19.830", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "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": "2022-11-20T05:15:11.810", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, {"source": "security@huntr.dev", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://huntr.dev/bounties/bb9f76db-1314-44ae-9ccc-2b69679aa657"}], "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/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, "type": "CWE-79"}
| 318
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"// Calculate filters\nuse LibreNMS\\Util\\Number;",
"$prev = ! empty($vars['period']) && ($vars['period'] == 'prev');\n$wheres = [];\n$param = [];\nif (isset($searchPhrase) && ! empty($searchPhrase)) {\n $wheres[] = 'bills.bill_name LIKE ?';\n $param[] = \"%$searchPhrase%\";\n}\nif (! empty($vars['bill_type'])) {\n if ($prev) {\n $wheres[] = 'bill_history.bill_type = ?';\n } else {\n $wheres[] = 'bill_type = ?';\n }\n $param[] = $vars['bill_type'];\n}\nif (! empty($vars['state'])) {\n if ($vars['state'] === 'under') {\n if ($prev) {\n $wheres[] = \"((bill_history.bill_type = 'cdr' AND bill_history.rate_95th <= bill_history.bill_allowed) OR (bill_history.bill_type = 'quota' AND bill_history.traf_total <= bill_history.bill_allowed))\";\n } else {\n $wheres[] = \"((bill_type = 'cdr' AND rate_95th <= bill_cdr) OR (bill_type = 'quota' AND total_data <= bill_quota))\";\n }\n } elseif ($vars['state'] === 'over') {\n if ($prev) {\n $wheres[] = \"((bill_history.bill_type = 'cdr' AND bill_history.rate_95th > bill_history.bill_allowed) OR (bill_history.bill_type = 'quota' AND bill_history.traf_total > bill_allowed))\";\n } else {\n $wheres[] = \"((bill_type = 'cdr' AND rate_95th > bill_cdr) OR (bill_type = 'quota' AND total_data > bill_quota))\";\n }\n }\n}",
"if ($prev) {\n $select = 'SELECT bills.bill_name, bills.bill_notes, bill_history.*, bill_history.traf_total as total_data, bill_history.traf_in as total_data_in, bill_history.traf_out as total_data_out ';\n $query = 'FROM `bills`\n INNER JOIN (SELECT bill_id, MAX(bill_hist_id) AS bill_hist_id FROM bill_history WHERE bill_dateto < NOW() AND bill_dateto > subdate(NOW(), 40) GROUP BY bill_id) qLastBills ON bills.bill_id = qLastBills.bill_id\n INNER JOIN bill_history ON qLastBills.bill_hist_id = bill_history.bill_hist_id\n';\n} else {\n $select = \"SELECT bills.*,\n IF(bills.bill_type = 'CDR', bill_cdr, bill_quota) AS bill_allowed\n \";\n $query = \"FROM `bills`\\n\";\n}",
"// Permissions check\nif (! Auth::user()->hasGlobalRead()) {\n $query .= ' INNER JOIN `bill_perms` AS `BP` ON `bills`.`bill_id` = `BP`.`bill_id` ';\n $wheres[] = '`BP`.`user_id`=?';\n $param[] = Auth::id();\n}",
"if (sizeof($wheres) > 0) {\n $query .= 'WHERE ' . implode(' AND ', $wheres) . \"\\n\";\n}\n$orderby = 'ORDER BY bills.bill_name';",
"$total = dbFetchCell(\"SELECT COUNT(bills.bill_id) $query\", $param);",
"$sql = \"$select\n$query\";",
"if (! isset($sort) || empty($sort)) {\n $sort = 'bills.bill_name';\n}",
"$sql .= \"\\nORDER BY $sort\";",
"if (isset($current)) {\n $limit_low = (($current * $rowCount) - ($rowCount));\n $limit_high = $rowCount;\n}",
"if ($rowCount != -1) {\n $sql .= \" LIMIT $limit_low,$limit_high\";\n}",
"foreach (dbFetchRows($sql, $param) as $bill) {\n if ($prev) {\n $datefrom = $bill['bill_datefrom'];\n $dateto = $bill['bill_dateto'];\n } else {\n $day_data = getDates($bill['bill_day']);\n $datefrom = $day_data['0'];\n $dateto = $day_data['1'];\n }\n $rate_95th = Number::formatSi($bill['rate_95th'], 2, 3, '') . 'bps';\n $dir_95th = $bill['dir_95th'];\n $total_data = format_bytes_billing($bill['total_data']);\n $rate_average = $bill['rate_average'];\n $url = \\LibreNMS\\Util\\Url::generate(['page' => 'bill', 'bill_id' => $bill['bill_id']]);\n $used95th = Number::formatSi($bill['rate_95th'], 2, 3, '') . 'bps';",
" $notes = $bill['bill_notes'];",
"\n if ($prev) {\n $percent = $bill['bill_percent'];\n $overuse = $bill['bill_overuse'];\n } else {\n }",
" if (strtolower($bill['bill_type']) == 'cdr') {\n $type = 'CDR';\n $allowed = Number::formatSi($bill['bill_allowed'], 2, 3, '') . 'bps';\n $in = Number::formatSi($bill['rate_95th_in'], 2, 3, '') . 'bps';\n $out = Number::formatSi($bill['rate_95th_out'], 2, 3, '') . 'bps';\n if (! $prev) {\n $percent = Number::calculatePercent($bill['rate_95th'], $bill['bill_allowed']);\n $overuse = ($bill['rate_95th'] - $bill['bill_allowed']);\n }",
" $overuse_formatted = Number::formatSi($overuse, 2, 3, '') . 'bps';\n $used = $rate_95th;\n $tmp_used = $bill['rate_95th'];\n $rate_95th = \"<b>$rate_95th</b>\";\n } elseif (strtolower($bill['bill_type']) == 'quota') {\n $type = 'Quota';\n $allowed = format_bytes_billing($bill['bill_allowed']);\n if (! empty($prev)) {\n $in = format_bytes_billing($bill['traf_in']);\n $out = format_bytes_billing($bill['traf_out']);\n } else {\n $in = format_bytes_billing($bill['total_data_in']);\n $out = format_bytes_billing($bill['total_data_out']);\n }\n if (! $prev) {\n $percent = Number::calculatePercent($bill['total_data'], $bill['bill_allowed']);\n $overuse = ($bill['total_data'] - $bill['bill_allowed']);\n }",
" $overuse_formatted = format_bytes_billing($overuse);\n $used = $total_data;\n $tmp_used = $bill['total_data'];\n $total_data = \"<b>$total_data</b>\";\n }",
" $background = \\LibreNMS\\Util\\Color::percentage($percent, null);\n $right_background = $background['right'];\n $left_background = $background['left'];\n $overuse_formatted = (($overuse <= 0) ? '-' : \"<span style='color: #${background['left']}; font-weight: bold;'>$overuse_formatted</span>\");\n",
" $bill_name = \"<a href='$url'><span style='font-weight: bold;' class='interface'>${bill['bill_name']}</span></a><br />\" .",
" date('Y-m-d', strtotime($datefrom)) . ' to ' . date('Y-m-d', strtotime($dateto));\n $bar = print_percentage_bar(250, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']);\n $actions = '';",
" if (! $prev && Auth::user()->hasGlobalAdmin()) {\n $actions .= \"<a href='\" . \\LibreNMS\\Util\\Url::generate(['page' => 'bill', 'bill_id' => $bill['bill_id'], 'view' => 'edit']) .\n \"'><i class='fa fa-pencil fa-lg icon-theme' title='Edit' aria-hidden='true'></i> Edit</a> \";\n }\n if (strtolower($bill['bill_type']) == 'cdr') {\n $predicted = Number::formatSi(getPredictedUsage($bill['bill_day'], $tmp_used), 2, 3, '') . 'bps';\n } elseif (strtolower($bill['bill_type']) == 'quota') {\n $predicted = format_bytes_billing(getPredictedUsage($bill['bill_day'], $tmp_used));\n }",
" $response[] = [\n 'bill_name' => $bill_name,\n 'notes' => $notes,\n 'bill_type' => $type,\n 'bill_allowed' => $allowed,\n 'total_data_in' => $in,\n 'total_data_out'=> $out,\n 'total_data' => $total_data,\n 'rate_95th' => $rate_95th,\n 'used' => $used,\n 'overusage' => $overuse_formatted,\n 'predicted' => $predicted,\n 'graph' => $bar,\n 'actions' => $actions,\n ];\n}",
"$output = ['current' => $current, 'rowCount' => $rowCount, 'rows' => $response, 'total' => $total];\necho json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [91, 107, 146], "buggy_code_start_loc": [90, 5, 97], "filenames": ["includes/html/pages/bill.inc.php", "includes/html/pages/bill/addoreditbill.inc.php", "includes/html/table/bills.inc.php"], "fixing_code_end_loc": [91, 107, 146], "fixing_code_start_loc": [90, 5, 97], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:librenms:librenms:*:*:*:*:*:*:*:*", "matchCriteriaId": "99D1C2AF-9BBB-4F7D-9FC3-4A645F7C284D", "versionEndExcluding": "22.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0."}], "evaluatorComment": null, "id": "CVE-2022-3562", "lastModified": "2022-11-21T13:19:19.830", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "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": "2022-11-20T05:15:11.810", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, {"source": "security@huntr.dev", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://huntr.dev/bounties/bb9f76db-1314-44ae-9ccc-2b69679aa657"}], "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/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, "type": "CWE-79"}
| 318
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"<?php",
"// Calculate filters\nuse LibreNMS\\Util\\Number;",
"$prev = ! empty($vars['period']) && ($vars['period'] == 'prev');\n$wheres = [];\n$param = [];\nif (isset($searchPhrase) && ! empty($searchPhrase)) {\n $wheres[] = 'bills.bill_name LIKE ?';\n $param[] = \"%$searchPhrase%\";\n}\nif (! empty($vars['bill_type'])) {\n if ($prev) {\n $wheres[] = 'bill_history.bill_type = ?';\n } else {\n $wheres[] = 'bill_type = ?';\n }\n $param[] = $vars['bill_type'];\n}\nif (! empty($vars['state'])) {\n if ($vars['state'] === 'under') {\n if ($prev) {\n $wheres[] = \"((bill_history.bill_type = 'cdr' AND bill_history.rate_95th <= bill_history.bill_allowed) OR (bill_history.bill_type = 'quota' AND bill_history.traf_total <= bill_history.bill_allowed))\";\n } else {\n $wheres[] = \"((bill_type = 'cdr' AND rate_95th <= bill_cdr) OR (bill_type = 'quota' AND total_data <= bill_quota))\";\n }\n } elseif ($vars['state'] === 'over') {\n if ($prev) {\n $wheres[] = \"((bill_history.bill_type = 'cdr' AND bill_history.rate_95th > bill_history.bill_allowed) OR (bill_history.bill_type = 'quota' AND bill_history.traf_total > bill_allowed))\";\n } else {\n $wheres[] = \"((bill_type = 'cdr' AND rate_95th > bill_cdr) OR (bill_type = 'quota' AND total_data > bill_quota))\";\n }\n }\n}",
"if ($prev) {\n $select = 'SELECT bills.bill_name, bills.bill_notes, bill_history.*, bill_history.traf_total as total_data, bill_history.traf_in as total_data_in, bill_history.traf_out as total_data_out ';\n $query = 'FROM `bills`\n INNER JOIN (SELECT bill_id, MAX(bill_hist_id) AS bill_hist_id FROM bill_history WHERE bill_dateto < NOW() AND bill_dateto > subdate(NOW(), 40) GROUP BY bill_id) qLastBills ON bills.bill_id = qLastBills.bill_id\n INNER JOIN bill_history ON qLastBills.bill_hist_id = bill_history.bill_hist_id\n';\n} else {\n $select = \"SELECT bills.*,\n IF(bills.bill_type = 'CDR', bill_cdr, bill_quota) AS bill_allowed\n \";\n $query = \"FROM `bills`\\n\";\n}",
"// Permissions check\nif (! Auth::user()->hasGlobalRead()) {\n $query .= ' INNER JOIN `bill_perms` AS `BP` ON `bills`.`bill_id` = `BP`.`bill_id` ';\n $wheres[] = '`BP`.`user_id`=?';\n $param[] = Auth::id();\n}",
"if (sizeof($wheres) > 0) {\n $query .= 'WHERE ' . implode(' AND ', $wheres) . \"\\n\";\n}\n$orderby = 'ORDER BY bills.bill_name';",
"$total = dbFetchCell(\"SELECT COUNT(bills.bill_id) $query\", $param);",
"$sql = \"$select\n$query\";",
"if (! isset($sort) || empty($sort)) {\n $sort = 'bills.bill_name';\n}",
"$sql .= \"\\nORDER BY $sort\";",
"if (isset($current)) {\n $limit_low = (($current * $rowCount) - ($rowCount));\n $limit_high = $rowCount;\n}",
"if ($rowCount != -1) {\n $sql .= \" LIMIT $limit_low,$limit_high\";\n}",
"foreach (dbFetchRows($sql, $param) as $bill) {\n if ($prev) {\n $datefrom = $bill['bill_datefrom'];\n $dateto = $bill['bill_dateto'];\n } else {\n $day_data = getDates($bill['bill_day']);\n $datefrom = $day_data['0'];\n $dateto = $day_data['1'];\n }\n $rate_95th = Number::formatSi($bill['rate_95th'], 2, 3, '') . 'bps';\n $dir_95th = $bill['dir_95th'];\n $total_data = format_bytes_billing($bill['total_data']);\n $rate_average = $bill['rate_average'];\n $url = \\LibreNMS\\Util\\Url::generate(['page' => 'bill', 'bill_id' => $bill['bill_id']]);\n $used95th = Number::formatSi($bill['rate_95th'], 2, 3, '') . 'bps';",
" $notes = htmlentities($bill['bill_notes']);",
"\n if ($prev) {\n $percent = $bill['bill_percent'];\n $overuse = $bill['bill_overuse'];\n } else {\n }",
" if (strtolower($bill['bill_type']) == 'cdr') {\n $type = 'CDR';\n $allowed = Number::formatSi($bill['bill_allowed'], 2, 3, '') . 'bps';\n $in = Number::formatSi($bill['rate_95th_in'], 2, 3, '') . 'bps';\n $out = Number::formatSi($bill['rate_95th_out'], 2, 3, '') . 'bps';\n if (! $prev) {\n $percent = Number::calculatePercent($bill['rate_95th'], $bill['bill_allowed']);\n $overuse = ($bill['rate_95th'] - $bill['bill_allowed']);\n }",
" $overuse_formatted = Number::formatSi($overuse, 2, 3, '') . 'bps';\n $used = $rate_95th;\n $tmp_used = $bill['rate_95th'];\n $rate_95th = \"<b>$rate_95th</b>\";\n } elseif (strtolower($bill['bill_type']) == 'quota') {\n $type = 'Quota';\n $allowed = format_bytes_billing($bill['bill_allowed']);\n if (! empty($prev)) {\n $in = format_bytes_billing($bill['traf_in']);\n $out = format_bytes_billing($bill['traf_out']);\n } else {\n $in = format_bytes_billing($bill['total_data_in']);\n $out = format_bytes_billing($bill['total_data_out']);\n }\n if (! $prev) {\n $percent = Number::calculatePercent($bill['total_data'], $bill['bill_allowed']);\n $overuse = ($bill['total_data'] - $bill['bill_allowed']);\n }",
" $overuse_formatted = format_bytes_billing($overuse);\n $used = $total_data;\n $tmp_used = $bill['total_data'];\n $total_data = \"<b>$total_data</b>\";\n }",
" $background = \\LibreNMS\\Util\\Color::percentage($percent, null);\n $right_background = $background['right'];\n $left_background = $background['left'];\n $overuse_formatted = (($overuse <= 0) ? '-' : \"<span style='color: #${background['left']}; font-weight: bold;'>$overuse_formatted</span>\");\n",
" $bill_name = \"<a href='$url'><span style='font-weight: bold;' class='interface'>\" . htmlentities($bill['bill_name']) . '</span></a><br />' .",
" date('Y-m-d', strtotime($datefrom)) . ' to ' . date('Y-m-d', strtotime($dateto));\n $bar = print_percentage_bar(250, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']);\n $actions = '';",
" if (! $prev && Auth::user()->hasGlobalAdmin()) {\n $actions .= \"<a href='\" . \\LibreNMS\\Util\\Url::generate(['page' => 'bill', 'bill_id' => $bill['bill_id'], 'view' => 'edit']) .\n \"'><i class='fa fa-pencil fa-lg icon-theme' title='Edit' aria-hidden='true'></i> Edit</a> \";\n }\n if (strtolower($bill['bill_type']) == 'cdr') {\n $predicted = Number::formatSi(getPredictedUsage($bill['bill_day'], $tmp_used), 2, 3, '') . 'bps';\n } elseif (strtolower($bill['bill_type']) == 'quota') {\n $predicted = format_bytes_billing(getPredictedUsage($bill['bill_day'], $tmp_used));\n }",
" $response[] = [\n 'bill_name' => $bill_name,\n 'notes' => $notes,\n 'bill_type' => $type,\n 'bill_allowed' => $allowed,\n 'total_data_in' => $in,\n 'total_data_out'=> $out,\n 'total_data' => $total_data,\n 'rate_95th' => $rate_95th,\n 'used' => $used,\n 'overusage' => $overuse_formatted,\n 'predicted' => $predicted,\n 'graph' => $bar,\n 'actions' => $actions,\n ];\n}",
"$output = ['current' => $current, 'rowCount' => $rowCount, 'rows' => $response, 'total' => $total];\necho json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);"
] |
[
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": [91, 107, 146], "buggy_code_start_loc": [90, 5, 97], "filenames": ["includes/html/pages/bill.inc.php", "includes/html/pages/bill/addoreditbill.inc.php", "includes/html/table/bills.inc.php"], "fixing_code_end_loc": [91, 107, 146], "fixing_code_start_loc": [90, 5, 97], "message": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:librenms:librenms:*:*:*:*:*:*:*:*", "matchCriteriaId": "99D1C2AF-9BBB-4F7D-9FC3-4A645F7C284D", "versionEndExcluding": "22.10.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Stored in GitHub repository librenms/librenms prior to 22.10.0."}], "evaluatorComment": null, "id": "CVE-2022-3562", "lastModified": "2022-11-21T13:19:19.830", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 3.4, "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": "2022-11-20T05:15:11.810", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, {"source": "security@huntr.dev", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://huntr.dev/bounties/bb9f76db-1314-44ae-9ccc-2b69679aa657"}], "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/librenms/librenms/commit/43cb72549d90e338f902b359a83c23d3cb5a2645"}, "type": "CWE-79"}
| 318
|
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 * indent.c: Indentation related functions\n */",
"#include \"vim.h\"",
"#if defined(FEAT_VARTABS) || defined(PROTO)",
"/*\n * Set the integer values corresponding to the string setting of 'vartabstop'.\n * \"array\" will be set, caller must free it if needed.\n * Return FAIL for an error.\n */\n int\ntabstop_set(char_u *var, int **array)\n{\n int\t valcount = 1;\n int\t t;\n char_u *cp;",
" if (var[0] == NUL || (var[0] == '0' && var[1] == NUL))\n {\n\t*array = NULL;\n\treturn OK;\n }",
" for (cp = var; *cp != NUL; ++cp)\n {\n\tif (cp == var || cp[-1] == ',')\n\t{\n\t char_u *end;",
"\t if (strtol((char *)cp, (char **)&end, 10) <= 0)\n\t {\n\t\tif (cp != end)\n\t\t emsg(_(e_argument_must_be_positive));\n\t\telse\n\t\t semsg(_(e_invalid_argument_str), cp);\n\t\treturn FAIL;\n\t }\n\t}",
"\tif (VIM_ISDIGIT(*cp))\n\t continue;\n\tif (cp[0] == ',' && cp > var && cp[-1] != ',' && cp[1] != NUL)\n\t{\n\t ++valcount;\n\t continue;\n\t}\n\tsemsg(_(e_invalid_argument_str), var);\n\treturn FAIL;\n }",
" *array = ALLOC_MULT(int, valcount + 1);\n if (*array == NULL)\n\treturn FAIL;\n (*array)[0] = valcount;",
" t = 1;\n for (cp = var; *cp != NUL;)\n {\n\tint n = atoi((char *)cp);",
"\t// Catch negative values, overflow and ridiculous big values.\n\tif (n <= 0 || n > TABSTOP_MAX)\n\t{\n\t semsg(_(e_invalid_argument_str), cp);\n\t vim_free(*array);\n\t *array = NULL;\n\t return FAIL;\n\t}\n\t(*array)[t++] = n;\n\twhile (*cp != NUL && *cp != ',')\n\t ++cp;\n\tif (*cp != NUL)\n\t ++cp;\n }",
" return OK;\n}",
"/*\n * Calculate the number of screen spaces a tab will occupy.\n * If \"vts\" is set then the tab widths are taken from that array,\n * otherwise the value of ts is used.\n */\n int\ntabstop_padding(colnr_T col, int ts_arg, int *vts)\n{\n int\t\tts = ts_arg == 0 ? 8 : ts_arg;\n int\t\ttabcount;\n colnr_T\ttabcol = 0;\n int\t\tt;\n int\t\tpadding = 0;",
" if (vts == NULL || vts[0] == 0)\n\treturn ts - (col % ts);",
" tabcount = vts[0];",
" for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > col)\n\t{\n\t padding = (int)(tabcol - col);\n\t break;\n\t}\n }\n if (t > tabcount)\n\tpadding = vts[tabcount] - (int)((col - tabcol) % vts[tabcount]);",
" return padding;\n}",
"/*\n * Find the size of the tab that covers a particular column.\n */\n int\ntabstop_at(colnr_T col, int ts, int *vts)\n{\n int\t\ttabcount;\n colnr_T\ttabcol = 0;\n int\t\tt;\n int\t\ttab_size = 0;",
" if (vts == 0 || vts[0] == 0)\n\treturn ts;",
" tabcount = vts[0];\n for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > col)\n\t{\n\t tab_size = vts[t];\n\t break;\n\t}\n }\n if (t > tabcount)\n\ttab_size = vts[tabcount];",
" return tab_size;\n}",
"/*\n * Find the column on which a tab starts.\n */\n colnr_T\ntabstop_start(colnr_T col, int ts, int *vts)\n{\n int\t\ttabcount;\n colnr_T\ttabcol = 0;\n int\t\tt;\n int\t\texcess;",
" if (vts == NULL || vts[0] == 0)\n\treturn (col / ts) * ts;",
" tabcount = vts[0];\n for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > col)\n\t return tabcol - vts[t];\n }",
" excess = tabcol % vts[tabcount];\n return excess + ((col - excess) / vts[tabcount]) * vts[tabcount];\n}",
"/*\n * Find the number of tabs and spaces necessary to get from one column\n * to another.\n */\n void\ntabstop_fromto(\n\tcolnr_T start_col,\n\tcolnr_T end_col,\n\tint\tts_arg,\n\tint\t*vts,\n\tint\t*ntabs,\n\tint\t*nspcs)\n{\n int\t\tspaces = end_col - start_col;\n colnr_T\ttabcol = 0;\n int\t\tpadding = 0;\n int\t\ttabcount;\n int\t\tt;\n int\t\tts = ts_arg == 0 ? curbuf->b_p_ts : ts_arg;",
" if (vts == NULL || vts[0] == 0)\n {\n\tint tabs = 0;\n\tint initspc = 0;",
"\tinitspc = ts - (start_col % ts);\n\tif (spaces >= initspc)\n\t{\n\t spaces -= initspc;\n\t tabs++;\n\t}\n\ttabs += spaces / ts;\n\tspaces -= (spaces / ts) * ts;",
"\t*ntabs = tabs;\n\t*nspcs = spaces;\n\treturn;\n }",
" // Find the padding needed to reach the next tabstop.\n tabcount = vts[0];\n for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > start_col)\n\t{\n\t padding = (int)(tabcol - start_col);\n\t break;\n\t}\n }\n if (t > tabcount)\n\tpadding = vts[tabcount] - (int)((start_col - tabcol) % vts[tabcount]);",
" // If the space needed is less than the padding no tabs can be used.\n if (spaces < padding)\n {\n\t*ntabs = 0;\n\t*nspcs = spaces;\n\treturn;\n }",
" *ntabs = 1;\n spaces -= padding;",
" // At least one tab has been used. See if any more will fit.\n while (spaces != 0 && ++t <= tabcount)\n {\n\tpadding = vts[t];\n\tif (spaces < padding)\n\t{\n\t *nspcs = spaces;\n\t return;\n\t}\n\t++*ntabs;\n\tspaces -= padding;\n }",
" *ntabs += spaces / vts[tabcount];\n *nspcs = spaces % vts[tabcount];\n}",
"/*\n * See if two tabstop arrays contain the same values.\n */\n static int\ntabstop_eq(int *ts1, int *ts2)\n{\n int\t\tt;",
" if ((ts1 == 0 && ts2) || (ts1 && ts2 == 0))\n\treturn FALSE;\n if (ts1 == ts2)\n\treturn TRUE;\n if (ts1[0] != ts2[0])\n\treturn FALSE;",
" for (t = 1; t <= ts1[0]; ++t)\n\tif (ts1[t] != ts2[t])\n\t return FALSE;",
" return TRUE;\n}",
"# if defined(FEAT_BEVAL) || defined(PROTO)\n/*\n * Copy a tabstop array, allocating space for the new array.\n */\n int *\ntabstop_copy(int *oldts)\n{\n int\t\t*newts;\n int\t\tt;",
" if (oldts == NULL)\n\treturn NULL;\n newts = ALLOC_MULT(int, oldts[0] + 1);\n if (newts != NULL)\n\tfor (t = 0; t <= oldts[0]; ++t)\n\t newts[t] = oldts[t];\n return newts;\n}\n# endif",
"/*\n * Return a count of the number of tabstops.\n */\n int\ntabstop_count(int *ts)\n{\n return ts != NULL ? ts[0] : 0;\n}",
"/*\n * Return the first tabstop, or 8 if there are no tabstops defined.\n */\n int\ntabstop_first(int *ts)\n{\n return ts != NULL ? ts[1] : 8;\n}",
"#endif",
"/*\n * Return the effective shiftwidth value for current buffer, using the\n * 'tabstop' value when 'shiftwidth' is zero.\n */\n long\nget_sw_value(buf_T *buf)\n{\n return get_sw_value_col(buf, 0);\n}",
"/*\n * Idem, using \"pos\".\n */\n static long\nget_sw_value_pos(buf_T *buf, pos_T *pos)\n{\n pos_T save_cursor = curwin->w_cursor;\n long sw_value;",
" curwin->w_cursor = *pos;\n sw_value = get_sw_value_col(buf, get_nolist_virtcol());\n curwin->w_cursor = save_cursor;\n return sw_value;\n}",
"/*\n * Idem, using the first non-black in the current line.\n */\n long\nget_sw_value_indent(buf_T *buf)\n{\n pos_T pos = curwin->w_cursor;",
" pos.col = getwhitecols_curline();\n return get_sw_value_pos(buf, &pos);\n}",
"/*\n * Idem, using virtual column \"col\".\n */\n long\nget_sw_value_col(buf_T *buf, colnr_T col UNUSED)\n{\n return buf->b_p_sw ? buf->b_p_sw :\n#ifdef FEAT_VARTABS\n\ttabstop_at(col, buf->b_p_ts, buf->b_p_vts_array);\n#else\n\tbuf->b_p_ts;\n#endif\n}",
"/*\n * Return the effective softtabstop value for the current buffer, using the\n * 'shiftwidth' value when 'softtabstop' is negative.\n */\n long\nget_sts_value(void)\n{\n return curbuf->b_p_sts < 0 ? get_sw_value(curbuf) : curbuf->b_p_sts;\n}",
"/*\n * Count the size (in window cells) of the indent in the current line.\n */\n int\nget_indent(void)\n{\n#ifdef FEAT_VARTABS\n return get_indent_str_vtab(ml_get_curline(), (int)curbuf->b_p_ts,\n\t\t\t\t\t\t curbuf->b_p_vts_array, FALSE);\n#else\n return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts, FALSE);\n#endif\n}",
"/*\n * Count the size (in window cells) of the indent in line \"lnum\".\n */\n int\nget_indent_lnum(linenr_T lnum)\n{\n#ifdef FEAT_VARTABS\n return get_indent_str_vtab(ml_get(lnum), (int)curbuf->b_p_ts,\n\t\t\t\t\t\t curbuf->b_p_vts_array, FALSE);\n#else\n return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts, FALSE);\n#endif\n}",
"#if defined(FEAT_FOLDING) || defined(PROTO)\n/*\n * Count the size (in window cells) of the indent in line \"lnum\" of buffer\n * \"buf\".\n */\n int\nget_indent_buf(buf_T *buf, linenr_T lnum)\n{\n# ifdef FEAT_VARTABS\n return get_indent_str_vtab(ml_get_buf(buf, lnum, FALSE),\n\t\t\t (int)curbuf->b_p_ts, buf->b_p_vts_array, FALSE);\n# else\n return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts, FALSE);\n# endif\n}\n#endif",
"/*\n * count the size (in window cells) of the indent in line \"ptr\", with\n * 'tabstop' at \"ts\"\n */\n int\nget_indent_str(\n char_u\t*ptr,\n int\t\tts,\n int\t\tlist) // if TRUE, count only screen size for tabs\n{\n int\t\tcount = 0;",
" for ( ; *ptr; ++ptr)\n {\n\tif (*ptr == TAB)\n\t{\n\t if (!list || curwin->w_lcs_chars.tab1)\n\t\t// count a tab for what it is worth\n\t\tcount += ts - (count % ts);\n\t else\n\t\t// In list mode, when tab is not set, count screen char width\n\t\t// for Tab, displays: ^I\n\t\tcount += ptr2cells(ptr);\n\t}\n\telse if (*ptr == ' ')\n\t ++count;\t\t// count a space for one\n\telse\n\t break;\n }\n return count;\n}",
"#ifdef FEAT_VARTABS\n/*\n * Count the size (in window cells) of the indent in line \"ptr\", using\n * variable tabstops.\n * if \"list\" is TRUE, count only screen size for tabs.\n */\n int\nget_indent_str_vtab(char_u *ptr, int ts, int *vts, int list)\n{\n int\t\tcount = 0;",
" for ( ; *ptr; ++ptr)\n {\n\tif (*ptr == TAB) // count a tab for what it is worth\n\t{\n\t if (!list || curwin->w_lcs_chars.tab1)\n\t\tcount += tabstop_padding(count, ts, vts);\n\t else\n\t\t// In list mode, when tab is not set, count screen char width\n\t\t// for Tab, displays: ^I\n\t\tcount += ptr2cells(ptr);\n\t}\n\telse if (*ptr == ' ')\n\t ++count;\t\t// count a space for one\n\telse\n\t break;\n }\n return count;\n}\n#endif",
"/*\n * Set the indent of the current line.\n * Leaves the cursor on the first non-blank in the line.\n * Caller must take care of undo.\n * \"flags\":\n *\tSIN_CHANGED:\tcall changed_bytes() if the line was changed.\n *\tSIN_INSERT:\tinsert the indent in front of the line.\n *\tSIN_UNDO:\tsave line for undo before changing it.\n * Returns TRUE if the line was changed.\n */\n int\nset_indent(\n int\t\tsize,\t\t // measured in spaces\n int\t\tflags)\n{\n char_u\t*p;\n char_u\t*newline;\n char_u\t*oldline;\n char_u\t*s;\n int\t\ttodo;\n int\t\tind_len;\t // measured in characters\n int\t\tline_len;\n int\t\tdoit = FALSE;\n int\t\tind_done = 0;\t // measured in spaces\n#ifdef FEAT_VARTABS\n int\t\tind_col = 0;\n#endif\n int\t\ttab_pad;\n int\t\tretval = FALSE;\n int\t\torig_char_len = -1; // number of initial whitespace chars when\n\t\t\t\t // 'et' and 'pi' are both set",
" // First check if there is anything to do and compute the number of\n // characters needed for the indent.\n todo = size;\n ind_len = 0;\n p = oldline = ml_get_curline();",
" // Calculate the buffer size for the new indent, and check to see if it\n // isn't already set",
" // if 'expandtab' isn't set: use TABs; if both 'expandtab' and\n // 'preserveindent' are set count the number of characters at the\n // beginning of the line to be copied\n if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))\n {\n\t// If 'preserveindent' is set then reuse as much as possible of\n\t// the existing indent structure for the new indent\n\tif (!(flags & SIN_INSERT) && curbuf->b_p_pi)\n\t{\n\t ind_done = 0;",
"\t // count as many characters as we can use\n\t while (todo > 0 && VIM_ISWHITE(*p))\n\t {\n\t\tif (*p == TAB)\n\t\t{\n#ifdef FEAT_VARTABS\n\t\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t\t tab_pad = (int)curbuf->b_p_ts\n\t\t\t\t\t - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t\t // stop if this tab will overshoot the target\n\t\t if (todo < tab_pad)\n\t\t\tbreak;\n\t\t todo -= tab_pad;\n\t\t ++ind_len;\n\t\t ind_done += tab_pad;\n\t\t}\n\t\telse\n\t\t{\n\t\t --todo;\n\t\t ++ind_len;\n\t\t ++ind_done;\n\t\t}\n\t\t++p;\n\t }",
"#ifdef FEAT_VARTABS\n\t // These diverge from this point.\n\t ind_col = ind_done;\n#endif\n\t // Set initial number of whitespace chars to copy if we are\n\t // preserving indent but expandtab is set\n\t if (curbuf->b_p_et)\n\t\torig_char_len = ind_len;",
"\t // Fill to next tabstop with a tab, if possible\n#ifdef FEAT_VARTABS\n\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t if (todo >= tab_pad && orig_char_len == -1)\n\t {\n\t\tdoit = TRUE;\n\t\ttodo -= tab_pad;\n\t\t++ind_len;\n\t\t// ind_done += tab_pad;\n#ifdef FEAT_VARTABS\n\t\tind_col += tab_pad;\n#endif\n\t }\n\t}",
"\t// count tabs required for indent\n#ifdef FEAT_VARTABS\n\tfor (;;)\n\t{\n\t tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n\t if (todo < tab_pad)\n\t\tbreak;\n\t if (*p != TAB)\n\t\tdoit = TRUE;\n\t else\n\t\t++p;\n\t todo -= tab_pad;\n\t ++ind_len;\n\t ind_col += tab_pad;\n\t}\n#else\n\twhile (todo >= (int)curbuf->b_p_ts)\n\t{\n\t if (*p != TAB)\n\t\tdoit = TRUE;\n\t else\n\t\t++p;\n\t todo -= (int)curbuf->b_p_ts;\n\t ++ind_len;\n\t // ind_done += (int)curbuf->b_p_ts;\n\t}\n#endif\n }\n // count spaces required for indent\n while (todo > 0)\n {\n\tif (*p != ' ')\n\t doit = TRUE;\n\telse\n\t ++p;\n\t--todo;\n\t++ind_len;\n\t// ++ind_done;\n }",
" // Return if the indent is OK already.\n if (!doit && !VIM_ISWHITE(*p) && !(flags & SIN_INSERT))\n\treturn FALSE;",
" // Allocate memory for the new line.\n if (flags & SIN_INSERT)\n\tp = oldline;\n else\n\tp = skipwhite(p);\n line_len = (int)STRLEN(p) + 1;",
" // If 'preserveindent' and 'expandtab' are both set keep the original\n // characters and allocate accordingly. We will fill the rest with spaces\n // after the if (!curbuf->b_p_et) below.\n if (orig_char_len != -1)\n {\n\tnewline = alloc(orig_char_len + size - ind_done + line_len);\n\tif (newline == NULL)\n\t return FALSE;\n\ttodo = size - ind_done;\n\tind_len = orig_char_len + todo; // Set total length of indent in\n\t\t\t\t\t // characters, which may have been\n\t\t\t\t\t // undercounted until now\n\tp = oldline;\n\ts = newline;\n\twhile (orig_char_len > 0)\n\t{\n\t *s++ = *p++;\n\t orig_char_len--;\n\t}",
"\t// Skip over any additional white space (useful when newindent is less\n\t// than old)\n\twhile (VIM_ISWHITE(*p))\n\t ++p;",
" }\n else\n {\n\ttodo = size;\n\tnewline = alloc(ind_len + line_len);\n\tif (newline == NULL)\n\t return FALSE;\n\ts = newline;\n }",
" // Put the characters in the new line.\n // if 'expandtab' isn't set: use TABs\n if (!curbuf->b_p_et)\n {\n\t// If 'preserveindent' is set then reuse as much as possible of\n\t// the existing indent structure for the new indent\n\tif (!(flags & SIN_INSERT) && curbuf->b_p_pi)\n\t{\n\t p = oldline;\n\t ind_done = 0;",
"\t while (todo > 0 && VIM_ISWHITE(*p))\n\t {\n\t\tif (*p == TAB)\n\t\t{\n#ifdef FEAT_VARTABS\n\t\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t\t tab_pad = (int)curbuf->b_p_ts\n\t\t\t\t\t - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t\t // stop if this tab will overshoot the target\n\t\t if (todo < tab_pad)\n\t\t\tbreak;\n\t\t todo -= tab_pad;\n\t\t ind_done += tab_pad;\n\t\t}\n\t\telse\n\t\t{\n\t\t --todo;\n\t\t ++ind_done;\n\t\t}\n\t\t*s++ = *p++;\n\t }",
"\t // Fill to next tabstop with a tab, if possible\n#ifdef FEAT_VARTABS\n\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t if (todo >= tab_pad)\n\t {\n\t\t*s++ = TAB;\n\t\ttodo -= tab_pad;\n#ifdef FEAT_VARTABS\n\t\tind_done += tab_pad;\n#endif\n\t }",
"\t p = skipwhite(p);\n\t}",
"#ifdef FEAT_VARTABS\n\tfor (;;)\n\t{\n\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n\t if (todo < tab_pad)\n\t\tbreak;\n\t *s++ = TAB;\n\t todo -= tab_pad;\n\t ind_done += tab_pad;\n\t}\n#else\n\twhile (todo >= (int)curbuf->b_p_ts)\n\t{\n\t *s++ = TAB;\n\t todo -= (int)curbuf->b_p_ts;\n\t}\n#endif\n }\n while (todo > 0)\n {\n\t*s++ = ' ';\n\t--todo;\n }\n mch_memmove(s, p, (size_t)line_len);",
" // Replace the line (unless undo fails).\n if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)\n {\n\tcolnr_T old_offset = (colnr_T)(p - oldline);\n\tcolnr_T new_offset = (colnr_T)(s - newline);",
"\t// this may free \"newline\"\n\tml_replace(curwin->w_cursor.lnum, newline, FALSE);\n\tif (flags & SIN_CHANGED)\n\t changed_bytes(curwin->w_cursor.lnum, 0);",
"\t// Correct saved cursor position if it is in this line.\n\tif (saved_cursor.lnum == curwin->w_cursor.lnum)\n\t{\n\t if (saved_cursor.col >= old_offset)\n\t\t// cursor was after the indent, adjust for the number of\n\t\t// bytes added/removed\n\t\tsaved_cursor.col += ind_len - old_offset;\n\t else if (saved_cursor.col >= new_offset)\n\t\t// cursor was in the indent, and is now after it, put it back\n\t\t// at the start of the indent (replacing spaces with TAB)\n\t\tsaved_cursor.col = new_offset;\n\t}\n#ifdef FEAT_PROP_POPUP\n\t{\n\t int added = ind_len - old_offset;",
"\t // When increasing indent this behaves like spaces were inserted at\n\t // the old indent, when decreasing indent it behaves like spaces\n\t // were deleted at the new indent.\n\t adjust_prop_columns(curwin->w_cursor.lnum,\n\t\t\t added > 0 ? old_offset : (colnr_T)ind_len, added, 0);\n\t}\n#endif\n\tretval = TRUE;\n }\n else\n\tvim_free(newline);",
" curwin->w_cursor.col = ind_len;\n return retval;\n}",
"/*\n * Return the indent of the current line after a number. Return -1 if no\n * number was found. Used for 'n' in 'formatoptions': numbered list.\n * Since a pattern is used it can actually handle more than numbers.\n */\n int\nget_number_indent(linenr_T lnum)\n{\n colnr_T\tcol;\n pos_T\tpos;",
" regmatch_T\tregmatch;\n int\t\tlead_len = 0;\t// length of comment leader",
" if (lnum > curbuf->b_ml.ml_line_count)\n\treturn -1;\n pos.lnum = 0;",
" // In format_lines() (i.e. not insert mode), fo+=q is needed too...\n if ((State & MODE_INSERT) || has_format_option(FO_Q_COMS))\n\tlead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);",
" regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);\n if (regmatch.regprog != NULL)\n {\n\tregmatch.rm_ic = FALSE;",
"\t// vim_regexec() expects a pointer to a line. This lets us\n\t// start matching for the flp beyond any comment leader...\n\tif (vim_regexec(®match, ml_get(lnum) + lead_len, (colnr_T)0))\n\t{\n\t pos.lnum = lnum;\n\t pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));\n\t pos.coladd = 0;\n\t}\n\tvim_regfree(regmatch.regprog);\n }",
" if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)\n\treturn -1;\n getvcol(curwin, &pos, &col, NULL, NULL);\n return (int)col;\n}",
"#if defined(FEAT_LINEBREAK) || defined(PROTO)\n/*\n * This is called when 'breakindentopt' is changed and when a window is\n * initialized.\n */\n int\nbriopt_check(win_T *wp)\n{\n char_u\t*p;\n int\t\tbri_shift = 0;\n long\tbri_min = 20;\n int\t\tbri_sbr = FALSE;\n int\t\tbri_list = 0;\n int\t\tbri_vcol = 0;",
" p = wp->w_p_briopt;\n while (*p != NUL)\n {\n\tif (STRNCMP(p, \"shift:\", 6) == 0\n\t\t && ((p[6] == '-' && VIM_ISDIGIT(p[7])) || VIM_ISDIGIT(p[6])))\n\t{\n\t p += 6;\n\t bri_shift = getdigits(&p);\n\t}\n\telse if (STRNCMP(p, \"min:\", 4) == 0 && VIM_ISDIGIT(p[4]))\n\t{\n\t p += 4;\n\t bri_min = getdigits(&p);\n\t}\n\telse if (STRNCMP(p, \"sbr\", 3) == 0)\n\t{\n\t p += 3;\n\t bri_sbr = TRUE;\n\t}\n\telse if (STRNCMP(p, \"list:\", 5) == 0)\n\t{\n\t p += 5;\n\t bri_list = getdigits(&p);\n\t}\n\telse if (STRNCMP(p, \"column:\", 7) == 0)\n\t{\n\t p += 7;\n\t bri_vcol = getdigits(&p);\n\t}\n\tif (*p != ',' && *p != NUL)\n\t return FAIL;\n\tif (*p == ',')\n\t ++p;\n }",
" wp->w_briopt_shift = bri_shift;\n wp->w_briopt_min = bri_min;\n wp->w_briopt_sbr = bri_sbr;\n wp->w_briopt_list = bri_list;\n wp->w_briopt_vcol = bri_vcol;",
" return OK;\n}",
"/*\n * Return appropriate space number for breakindent, taking influencing\n * parameters into account. Window must be specified, since it is not\n * necessarily always the current one.\n */\n int\nget_breakindent_win(\n win_T\t*wp,\n char_u\t*line) // start of the line\n{\n static int\t prev_indent = 0;\t// cached indent value\n static long\t prev_ts = 0L;\t// cached tabstop value\n static char_u *prev_line = NULL;\t// cached pointer to line\n static varnumber_T prev_tick = 0; // changedtick of cached value\n# ifdef FEAT_VARTABS\n static int *prev_vts = NULL; // cached vartabs values\n# endif\n static int prev_list = 0;\t// cached list value\n static int prev_listopt = 0;\t// cached w_p_briopt_list value\n // cached formatlistpat value\n static char_u *prev_flp = NULL;\n int\t\t bri = 0;\n // window width minus window margin space, i.e. what rests for text\n const int\t eff_wwidth = wp->w_width\n\t\t\t - ((wp->w_p_nu || wp->w_p_rnu)\n\t\t\t\t&& (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)\n\t\t\t\t\t\t? number_width(wp) + 1 : 0);",
" // used cached indent, unless\n // - line pointer changed\n // - 'tabstop' changed\n // - 'briopt_list changed' changed or\n // - 'formatlistpattern' changed\n if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts\n\t || prev_tick != CHANGEDTICK(wp->w_buffer)\n\t || prev_listopt != wp->w_briopt_list\n\t || (prev_flp == NULL\n\t\t|| (STRCMP(prev_flp, get_flp_value(wp->w_buffer)) != 0))\n# ifdef FEAT_VARTABS\n\t || prev_vts != wp->w_buffer->b_p_vts_array\n# endif\n\t)\n {\n\tprev_line = line;\n\tprev_ts = wp->w_buffer->b_p_ts;\n\tprev_tick = CHANGEDTICK(wp->w_buffer);\n# ifdef FEAT_VARTABS\n\tprev_vts = wp->w_buffer->b_p_vts_array;\n\tif (wp->w_briopt_vcol == 0)\n\t prev_indent = get_indent_str_vtab(line,\n\t\t\t\t (int)wp->w_buffer->b_p_ts,\n\t\t\t\t wp->w_buffer->b_p_vts_array, wp->w_p_list);\n# else\n\tif (wp->w_briopt_vcol == 0)\n\t prev_indent = get_indent_str(line,\n\t\t\t\t (int)wp->w_buffer->b_p_ts, wp->w_p_list);\n# endif\n\tprev_listopt = wp->w_briopt_list;\n\tprev_list = 0;\n\tvim_free(prev_flp);\n\tprev_flp = vim_strsave(get_flp_value(wp->w_buffer));\n\t// add additional indent for numbered lists\n\tif (wp->w_briopt_list != 0 && wp->w_briopt_vcol == 0)\n\t{\n\t regmatch_T\t regmatch;",
"\t regmatch.regprog = vim_regcomp(prev_flp,\n\t\t\t\t RE_MAGIC + RE_STRING + RE_AUTO + RE_STRICT);",
"\t if (regmatch.regprog != NULL)\n\t {\n\t\tregmatch.rm_ic = FALSE;\n\t\tif (vim_regexec(®match, line, 0))\n\t\t{\n\t\t if (wp->w_briopt_list > 0)\n\t\t\tprev_list = wp->w_briopt_list;\n\t\t else\n\t\t\tprev_list = (*regmatch.endp - *regmatch.startp);\n\t\t}\n\t\tvim_regfree(regmatch.regprog);\n\t }\n\t}\n }\n if (wp->w_briopt_vcol != 0)\n {\n\t// column value has priority\n\tbri = wp->w_briopt_vcol;\n\tprev_list = 0;\n }\n else\n\tbri = prev_indent + wp->w_briopt_shift;",
" // Add offset for number column, if 'n' is in 'cpoptions'\n bri += win_col_off2(wp);",
" // add additional indent for numbered lists\n if (wp->w_briopt_list != 0)\n {\n\tif (wp->w_briopt_list > 0)\n\t bri += prev_list;\n\telse\n\t bri = prev_list;\n }",
" // indent minus the length of the showbreak string\n if (wp->w_briopt_sbr)\n\tbri -= vim_strsize(get_showbreak_value(wp));",
"\n // never indent past left window margin\n if (bri < 0)\n\tbri = 0;",
" // always leave at least bri_min characters on the left,\n // if text width is sufficient\n else if (bri > eff_wwidth - wp->w_briopt_min)\n\tbri = (eff_wwidth - wp->w_briopt_min < 0)\n\t\t\t\t\t ? 0 : eff_wwidth - wp->w_briopt_min;",
" return bri;\n}\n#endif",
"/*\n * When extra == 0: Return TRUE if the cursor is before or on the first\n *\t\t non-blank in the line.\n * When extra == 1: Return TRUE if the cursor is before the first non-blank in\n *\t\t the line.\n */\n int\ninindent(int extra)\n{\n char_u\t*ptr;\n colnr_T\tcol;",
" for (col = 0, ptr = ml_get_curline(); VIM_ISWHITE(*ptr); ++col)\n\t++ptr;\n if (col >= curwin->w_cursor.col + extra)\n\treturn TRUE;\n else\n\treturn FALSE;\n}",
"/*\n * op_reindent - handle reindenting a block of lines.\n */\n void\nop_reindent(oparg_T *oap, int (*how)(void))\n{\n long\ti = 0;\n char_u\t*l;\n int\t\tamount;\n linenr_T\tfirst_changed = 0;\n linenr_T\tlast_changed = 0;\n linenr_T\tstart_lnum = curwin->w_cursor.lnum;",
" // Don't even try when 'modifiable' is off.\n if (!curbuf->b_p_ma)\n {\n\temsg(_(e_cannot_make_changes_modifiable_is_off));\n\treturn;\n }",
" // Save for undo. Do this once for all lines, much faster than doing this\n // for each line separately, especially when undoing.\n if (u_savecommon(start_lnum - 1, start_lnum + oap->line_count,\n\t\t\t\t start_lnum + oap->line_count, FALSE) == OK)\n\tfor (i = oap->line_count; --i >= 0 && !got_int; )\n\t{\n\t // it's a slow thing to do, so give feedback so there's no worry\n\t // that the computer's just hung.",
"\t if (i > 1\n\t\t && (i % 50 == 0 || i == oap->line_count - 1)\n\t\t && oap->line_count > p_report)\n\t\tsmsg(_(\"%ld lines to indent... \"), i);",
"\t // Be vi-compatible: For lisp indenting the first line is not\n\t // indented, unless there is only one line.\n\t if (i != oap->line_count - 1 || oap->line_count == 1\n\t\t\t\t\t\t || how != get_lisp_indent)\n\t {\n\t\tl = skipwhite(ml_get_curline());\n\t\tif (*l == NUL)\t\t // empty or blank line\n\t\t amount = 0;\n\t\telse\n\t\t amount = how();\t // get the indent for this line",
"\t\tif (amount >= 0 && set_indent(amount, 0))\n\t\t{\n\t\t // did change the indent, call changed_lines() later\n\t\t if (first_changed == 0)\n\t\t\tfirst_changed = curwin->w_cursor.lnum;\n\t\t last_changed = curwin->w_cursor.lnum;\n\t\t}\n\t }\n\t ++curwin->w_cursor.lnum;\n\t curwin->w_cursor.col = 0; // make sure it's valid\n\t}",
" // put cursor on first non-blank of indented line\n curwin->w_cursor.lnum = start_lnum;\n beginline(BL_SOL | BL_FIX);",
" // Mark changed lines so that they will be redrawn. When Visual\n // highlighting was present, need to continue until the last line. When\n // there is no change still need to remove the Visual highlighting.\n if (last_changed != 0)\n\tchanged_lines(first_changed, 0,\n\t\toap->is_VIsual ? start_lnum + oap->line_count :\n\t\tlast_changed + 1, 0L);\n else if (oap->is_VIsual)\n\tredraw_curbuf_later(INVERTED);",
" if (oap->line_count > p_report)\n {\n\ti = oap->line_count - (i + 1);\n\tsmsg(NGETTEXT(\"%ld line indented \",\n\t\t\t\t\t\t \"%ld lines indented \", i), i);\n }\n if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n {\n\t// set '[ and '] marks\n\tcurbuf->b_op_start = oap->start;\n\tcurbuf->b_op_end = oap->end;\n }\n}",
"/*\n * Return TRUE if lines starting with '#' should be left aligned.\n */\n int\npreprocs_left(void)\n{\n return\n\t(curbuf->b_p_si && !curbuf->b_p_cin) ||\n\t(curbuf->b_p_cin && in_cinkeys('#', ' ', TRUE)\n\t\t\t\t\t && curbuf->b_ind_hash_comment == 0)\n\t;\n}",
"/*\n * Return TRUE if the conditions are OK for smart indenting.\n */\n int\nmay_do_si()\n{\n return curbuf->b_p_si\n\t&& !curbuf->b_p_cin\n# ifdef FEAT_EVAL\n\t&& *curbuf->b_p_inde == NUL\n# endif\n\t&& !p_paste;\n}",
"/*\n * Try to do some very smart auto-indenting.\n * Used when inserting a \"normal\" character.\n */\n void\nins_try_si(int c)\n{\n pos_T\t*pos, old_pos;\n char_u\t*ptr;\n int\t\ti;\n int\t\ttemp;",
" // do some very smart indenting when entering '{' or '}'\n if (((did_si || can_si_back) && c == '{')\n\t || (can_si && c == '}' && inindent(0)))\n {\n\t// for '}' set indent equal to indent of line containing matching '{'\n\tif (c == '}' && (pos = findmatch(NULL, '{')) != NULL)\n\t{\n\t old_pos = curwin->w_cursor;\n\t // If the matching '{' has a ')' immediately before it (ignoring\n\t // white-space), then line up with the start of the line\n\t // containing the matching '(' if there is one. This handles the\n\t // case where an \"if (..\\n..) {\" statement continues over multiple\n\t // lines -- webb\n\t ptr = ml_get(pos->lnum);\n\t i = pos->col;\n\t if (i > 0)\t\t// skip blanks before '{'\n\t\twhile (--i > 0 && VIM_ISWHITE(ptr[i]))\n\t\t ;\n\t curwin->w_cursor.lnum = pos->lnum;\n\t curwin->w_cursor.col = i;\n\t if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)\n\t\tcurwin->w_cursor = *pos;\n\t i = get_indent();\n\t curwin->w_cursor = old_pos;\n\t if (State & VREPLACE_FLAG)\n\t\tchange_indent(INDENT_SET, i, FALSE, NUL, TRUE);\n\t else\n\t\t(void)set_indent(i, SIN_CHANGED);\n\t}\n\telse if (curwin->w_cursor.col > 0)\n\t{\n\t // when inserting '{' after \"O\" reduce indent, but not\n\t // more than indent of previous line\n\t temp = TRUE;\n\t if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)\n\t {\n\t\told_pos = curwin->w_cursor;\n\t\ti = get_indent();\n\t\twhile (curwin->w_cursor.lnum > 1)\n\t\t{\n\t\t ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));",
"\t\t // ignore empty lines and lines starting with '#'.\n\t\t if (*ptr != '#' && *ptr != NUL)\n\t\t\tbreak;\n\t\t}\n\t\tif (get_indent() >= i)\n\t\t temp = FALSE;\n\t\tcurwin->w_cursor = old_pos;\n\t }\n\t if (temp)\n\t\tshift_line(TRUE, FALSE, 1, TRUE);\n\t}\n }",
" // set indent of '#' always to 0\n if (curwin->w_cursor.col > 0 && can_si && c == '#' && inindent(0))\n {\n\t// remember current indent for next line\n\told_indent = get_indent();\n\t(void)set_indent(0, SIN_CHANGED);\n }",
" // Adjust ai_col, the char at this position can be deleted.\n if (ai_col > curwin->w_cursor.col)\n\tai_col = curwin->w_cursor.col;\n}",
"/*\n * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).\n * Keep the cursor on the same character.\n * type == INDENT_INC\tincrease indent (for CTRL-T or <Tab>)\n * type == INDENT_DEC\tdecrease indent (for CTRL-D)\n * type == INDENT_SET\tset indent to \"amount\"\n * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).\n */\n void\nchange_indent(\n int\t\ttype,\n int\t\tamount,\n int\t\tround,\n int\t\treplaced,\t// replaced character, put on replace stack\n int\t\tcall_changed_bytes)\t// call changed_bytes()\n{\n int\t\tvcol;\n int\t\tlast_vcol;\n int\t\tinsstart_less;\t\t// reduction for Insstart.col\n int\t\tnew_cursor_col;\n int\t\ti;\n char_u\t*ptr;\n int\t\tsave_p_list;\n int\t\tstart_col;\n colnr_T\tvc;\n colnr_T\torig_col = 0;\t\t// init for GCC\n char_u\t*new_line, *orig_line = NULL;\t// init for GCC",
" // MODE_VREPLACE state needs to know what the line was like before changing\n if (State & VREPLACE_FLAG)\n {\n\torig_line = vim_strsave(ml_get_curline()); // Deal with NULL below\n\torig_col = curwin->w_cursor.col;\n }",
" // for the following tricks we don't want list mode\n save_p_list = curwin->w_p_list;\n curwin->w_p_list = FALSE;\n vc = getvcol_nolist(&curwin->w_cursor);\n vcol = vc;",
" // For Replace mode we need to fix the replace stack later, which is only\n // possible when the cursor is in the indent. Remember the number of\n // characters before the cursor if it's possible.\n start_col = curwin->w_cursor.col;",
" // determine offset from first non-blank\n new_cursor_col = curwin->w_cursor.col;\n beginline(BL_WHITE);\n new_cursor_col -= curwin->w_cursor.col;",
" insstart_less = curwin->w_cursor.col;",
" // If the cursor is in the indent, compute how many screen columns the\n // cursor is to the left of the first non-blank.\n if (new_cursor_col < 0)\n\tvcol = get_indent() - vcol;",
" if (new_cursor_col > 0)\t // can't fix replace stack\n\tstart_col = -1;",
" // Set the new indent. The cursor will be put on the first non-blank.\n if (type == INDENT_SET)\n\t(void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);\n else\n {\n\tint\tsave_State = State;",
"\t// Avoid being called recursively.\n\tif (State & VREPLACE_FLAG)\n\t State = MODE_INSERT;\n\tshift_line(type == INDENT_DEC, round, 1, call_changed_bytes);\n\tState = save_State;\n }\n insstart_less -= curwin->w_cursor.col;",
" // Try to put cursor on same character.\n // If the cursor is at or after the first non-blank in the line,\n // compute the cursor column relative to the column of the first\n // non-blank character.\n // If we are not in insert mode, leave the cursor on the first non-blank.\n // If the cursor is before the first non-blank, position it relative\n // to the first non-blank, counted in screen columns.\n if (new_cursor_col >= 0)\n {\n\t// When changing the indent while the cursor is touching it, reset\n\t// Insstart_col to 0.\n\tif (new_cursor_col == 0)\n\t insstart_less = MAXCOL;\n\tnew_cursor_col += curwin->w_cursor.col;\n }\n else if (!(State & MODE_INSERT))\n\tnew_cursor_col = curwin->w_cursor.col;\n else\n {\n\t// Compute the screen column where the cursor should be.\n\tvcol = get_indent() - vcol;\n\tcurwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);",
"\t// Advance the cursor until we reach the right screen column.\n\tvcol = last_vcol = 0;\n\tnew_cursor_col = -1;\n\tptr = ml_get_curline();\n\twhile (vcol <= (int)curwin->w_virtcol)\n\t{\n\t last_vcol = vcol;\n\t if (has_mbyte && new_cursor_col >= 0)\n\t\tnew_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);\n\t else\n\t\t++new_cursor_col;\n\t if (ptr[new_cursor_col] == NUL)\n\t\tbreak;\n\t vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol);\n\t}\n\tvcol = last_vcol;",
"\t// May need to insert spaces to be able to position the cursor on\n\t// the right screen column.\n\tif (vcol != (int)curwin->w_virtcol)\n\t{\n\t curwin->w_cursor.col = (colnr_T)new_cursor_col;\n\t i = (int)curwin->w_virtcol - vcol;\n\t ptr = alloc(i + 1);\n\t if (ptr != NULL)\n\t {\n\t\tnew_cursor_col += i;\n\t\tptr[i] = NUL;\n\t\twhile (--i >= 0)\n\t\t ptr[i] = ' ';\n\t\tins_str(ptr);\n\t\tvim_free(ptr);\n\t }\n\t}",
"\t// When changing the indent while the cursor is in it, reset\n\t// Insstart_col to 0.\n\tinsstart_less = MAXCOL;\n }",
" curwin->w_p_list = save_p_list;",
" if (new_cursor_col <= 0)\n\tcurwin->w_cursor.col = 0;\n else\n\tcurwin->w_cursor.col = (colnr_T)new_cursor_col;\n curwin->w_set_curswant = TRUE;\n changed_cline_bef_curs();",
" // May have to adjust the start of the insert.\n if (State & MODE_INSERT)\n {\n\tif (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)\n\t{\n\t if ((int)Insstart.col <= insstart_less)\n\t\tInsstart.col = 0;\n\t else\n\t\tInsstart.col -= insstart_less;\n\t}\n\tif ((int)ai_col <= insstart_less)\n\t ai_col = 0;\n\telse\n\t ai_col -= insstart_less;\n }",
" // For MODE_REPLACE state, may have to fix the replace stack, if it's\n // possible. If the number of characters before the cursor decreased, need\n // to pop a few characters from the replace stack.\n // If the number of characters before the cursor increased, need to push a\n // few NULs onto the replace stack.\n if (REPLACE_NORMAL(State) && start_col >= 0)\n {\n\twhile (start_col > (int)curwin->w_cursor.col)\n\t{\n\t replace_join(0);\t // remove a NUL from the replace stack\n\t --start_col;\n\t}\n\twhile (start_col < (int)curwin->w_cursor.col || replaced)\n\t{\n\t replace_push(NUL);\n\t if (replaced)\n\t {\n\t\treplace_push(replaced);\n\t\treplaced = NUL;\n\t }\n\t ++start_col;\n\t}\n }",
" // For MODE_VREPLACE state, we also have to fix the replace stack. In this\n // case it is always possible because we backspace over the whole line and\n // then put it back again the way we wanted it.\n if (State & VREPLACE_FLAG)\n {\n\t// If orig_line didn't allocate, just return. At least we did the job,\n\t// even if you can't backspace.\n\tif (orig_line == NULL)\n\t return;",
"\t// Save new line\n\tnew_line = vim_strsave(ml_get_curline());\n\tif (new_line == NULL)\n\t return;",
"\t// We only put back the new line up to the cursor\n\tnew_line[curwin->w_cursor.col] = NUL;",
"\t// Put back original line\n\tml_replace(curwin->w_cursor.lnum, orig_line, FALSE);\n\tcurwin->w_cursor.col = orig_col;",
"\t// Backspace from cursor to start of line\n\tbackspace_until_column(0);",
"\t// Insert new stuff into line again\n\tins_bytes(new_line);",
"\tvim_free(new_line);\n }\n}",
"/*\n * Copy the indent from ptr to the current line (and fill to size)\n * Leaves the cursor on the first non-blank in the line.\n * Returns TRUE if the line was changed.\n */\n int\ncopy_indent(int size, char_u *src)\n{\n char_u\t*p = NULL;\n char_u\t*line = NULL;\n char_u\t*s;\n int\t\ttodo;\n int\t\tind_len;\n int\t\tline_len = 0;\n int\t\ttab_pad;\n int\t\tind_done;\n int\t\tround;\n#ifdef FEAT_VARTABS\n int\t\tind_col;\n#endif",
" // Round 1: compute the number of characters needed for the indent\n // Round 2: copy the characters.\n for (round = 1; round <= 2; ++round)\n {\n\ttodo = size;\n\tind_len = 0;\n\tind_done = 0;\n#ifdef FEAT_VARTABS\n\tind_col = 0;\n#endif\n\ts = src;",
"\t// Count/copy the usable portion of the source line\n\twhile (todo > 0 && VIM_ISWHITE(*s))\n\t{\n\t if (*s == TAB)\n\t {\n#ifdef FEAT_VARTABS\n\t\ttab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t\ttab_pad = (int)curbuf->b_p_ts\n\t\t\t\t\t - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t\t// Stop if this tab will overshoot the target\n\t\tif (todo < tab_pad)\n\t\t break;\n\t\ttodo -= tab_pad;\n\t\tind_done += tab_pad;\n#ifdef FEAT_VARTABS\n\t\tind_col += tab_pad;\n#endif\n\t }\n\t else\n\t {\n\t\t--todo;\n\t\t++ind_done;\n#ifdef FEAT_VARTABS\n\t\t++ind_col;\n#endif\n\t }\n\t ++ind_len;\n\t if (p != NULL)\n\t\t*p++ = *s;\n\t ++s;\n\t}",
"\t// Fill to next tabstop with a tab, if possible\n#ifdef FEAT_VARTABS\n\ttab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\ttab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\tif (todo >= tab_pad && !curbuf->b_p_et)\n\t{\n\t todo -= tab_pad;\n\t ++ind_len;\n#ifdef FEAT_VARTABS\n\t ind_col += tab_pad;\n#endif\n\t if (p != NULL)\n\t\t*p++ = TAB;\n\t}",
"\t// Add tabs required for indent\n\tif (!curbuf->b_p_et)\n\t{\n#ifdef FEAT_VARTABS\n\t for (;;)\n\t {\n\t\ttab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n\t\tif (todo < tab_pad)\n\t\t break;\n\t\ttodo -= tab_pad;\n\t\t++ind_len;\n\t\tind_col += tab_pad;\n\t\tif (p != NULL)\n\t\t *p++ = TAB;\n\t }\n#else\n\t while (todo >= (int)curbuf->b_p_ts)\n\t {\n\t\ttodo -= (int)curbuf->b_p_ts;\n\t\t++ind_len;\n\t\tif (p != NULL)\n\t\t *p++ = TAB;\n\t }\n#endif\n\t}",
"\t// Count/add spaces required for indent\n\twhile (todo > 0)\n\t{\n\t --todo;\n\t ++ind_len;\n\t if (p != NULL)\n\t\t*p++ = ' ';\n\t}",
"\tif (p == NULL)\n\t{\n\t // Allocate memory for the result: the copied indent, new indent\n\t // and the rest of the line.\n\t line_len = (int)STRLEN(ml_get_curline()) + 1;\n\t line = alloc(ind_len + line_len);\n\t if (line == NULL)\n\t\treturn FALSE;\n\t p = line;\n\t}\n }",
" // Append the original line\n mch_memmove(p, ml_get_curline(), (size_t)line_len);",
" // Replace the line\n ml_replace(curwin->w_cursor.lnum, line, FALSE);",
" // Put the cursor after the indent.\n curwin->w_cursor.col = ind_len;\n return TRUE;\n}",
"/*\n * Give a \"resulting text too long\" error and maybe set got_int.\n */\n static void\nemsg_text_too_long(void)\n{\n emsg(_(e_resulting_text_too_long));\n#ifdef FEAT_EVAL\n // when not inside a try/catch set got_int to break out of any loop\n if (trylevel == 0)\n#endif\n\tgot_int = TRUE;\n}",
"/*\n * \":retab\".\n */\n void\nex_retab(exarg_T *eap)\n{\n linenr_T\tlnum;\n int\t\tgot_tab = FALSE;\n long\tnum_spaces = 0;\n long\tnum_tabs;\n long\tlen;\n long\tcol;\n long\tvcol;\n long\tstart_col = 0;\t\t// For start of white-space string\n long\tstart_vcol = 0;\t\t// For start of white-space string\n long\told_len;\n long\tnew_len;\n char_u\t*ptr;\n char_u\t*new_line = (char_u *)1; // init to non-NULL\n int\t\tdid_undo;\t\t// called u_save for current line\n#ifdef FEAT_VARTABS\n int\t\t*new_vts_array = NULL;\n char_u\t*new_ts_str;\t\t// string value of tab argument\n#else\n int\t\ttemp;\n int\t\tnew_ts;\n#endif\n int\t\tsave_list;\n linenr_T\tfirst_line = 0;\t\t// first changed line\n linenr_T\tlast_line = 0;\t\t// last changed line",
" save_list = curwin->w_p_list;\n curwin->w_p_list = 0;\t // don't want list mode here",
"#ifdef FEAT_VARTABS\n new_ts_str = eap->arg;\n if (tabstop_set(eap->arg, &new_vts_array) == FAIL)\n\treturn;\n while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')\n\t++(eap->arg);",
" // This ensures that either new_vts_array and new_ts_str are freshly\n // allocated, or new_vts_array points to an existing array and new_ts_str\n // is null.\n if (new_vts_array == NULL)\n {\n\tnew_vts_array = curbuf->b_p_vts_array;\n\tnew_ts_str = NULL;\n }\n else\n\tnew_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str);\n#else\n ptr = eap->arg;\n new_ts = getdigits(&ptr);\n if (new_ts < 0 && *eap->arg == '-')\n {\n\temsg(_(e_argument_must_be_positive));\n\treturn;\n }\n if (new_ts < 0 || new_ts > TABSTOP_MAX)\n {\n\tsemsg(_(e_invalid_argument_str), eap->arg);\n\treturn;\n }\n if (new_ts == 0)\n\tnew_ts = curbuf->b_p_ts;\n#endif\n for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)\n {\n\tptr = ml_get(lnum);\n\tcol = 0;\n\tvcol = 0;\n\tdid_undo = FALSE;\n\tfor (;;)\n\t{\n\t if (VIM_ISWHITE(ptr[col]))\n\t {\n\t\tif (!got_tab && num_spaces == 0)\n\t\t{\n\t\t // First consecutive white-space\n\t\t start_vcol = vcol;\n\t\t start_col = col;\n\t\t}\n\t\tif (ptr[col] == ' ')\n\t\t num_spaces++;\n\t\telse\n\t\t got_tab = TRUE;\n\t }\n\t else\n\t {\n\t\tif (got_tab || (eap->forceit && num_spaces > 1))\n\t\t{\n\t\t // Retabulate this string of white-space",
"\t\t // len is virtual length of white string\n\t\t len = num_spaces = vcol - start_vcol;\n\t\t num_tabs = 0;\n\t\t if (!curbuf->b_p_et)\n\t\t {\n#ifdef FEAT_VARTABS\n\t\t\tint t, s;",
"\t\t\ttabstop_fromto(start_vcol, vcol,\n\t\t\t\t\tcurbuf->b_p_ts, new_vts_array, &t, &s);\n\t\t\tnum_tabs = t;\n\t\t\tnum_spaces = s;\n#else\n\t\t\ttemp = new_ts - (start_vcol % new_ts);\n\t\t\tif (num_spaces >= temp)\n\t\t\t{\n\t\t\t num_spaces -= temp;\n\t\t\t num_tabs++;\n\t\t\t}\n\t\t\tnum_tabs += num_spaces / new_ts;\n\t\t\tnum_spaces -= (num_spaces / new_ts) * new_ts;\n#endif\n\t\t }\n\t\t if (curbuf->b_p_et || got_tab ||\n\t\t\t\t\t(num_spaces + num_tabs < len))\n\t\t {\n\t\t\tif (did_undo == FALSE)\n\t\t\t{\n\t\t\t did_undo = TRUE;\n\t\t\t if (u_save((linenr_T)(lnum - 1),\n\t\t\t\t\t\t(linenr_T)(lnum + 1)) == FAIL)\n\t\t\t {\n\t\t\t\tnew_line = NULL;\t// flag out-of-memory\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}",
"\t\t\t// len is actual number of white characters used\n\t\t\tlen = num_spaces + num_tabs;\n\t\t\told_len = (long)STRLEN(ptr);\n\t\t\tnew_len = old_len - col + start_col + len + 1;\n\t\t\tif (new_len <= 0 || new_len >= MAXCOL)\n\t\t\t{\n\t\t\t emsg_text_too_long();\n\t\t\t break;\n\t\t\t}\n\t\t\tnew_line = alloc(new_len);\n\t\t\tif (new_line == NULL)\n\t\t\t break;\n\t\t\tif (start_col > 0)\n\t\t\t mch_memmove(new_line, ptr, (size_t)start_col);\n\t\t\tmch_memmove(new_line + start_col + len,\n\t\t\t\t ptr + col, (size_t)(old_len - col + 1));\n\t\t\tptr = new_line + start_col;\n\t\t\tfor (col = 0; col < len; col++)\n\t\t\t ptr[col] = (col < num_tabs) ? '\\t' : ' ';\n\t\t\tif (ml_replace(lnum, new_line, FALSE) == OK)\n\t\t\t // \"new_line\" may have been copied\n\t\t\t new_line = curbuf->b_ml.ml_line_ptr;\n\t\t\tif (first_line == 0)\n\t\t\t first_line = lnum;\n\t\t\tlast_line = lnum;\n\t\t\tptr = new_line;\n\t\t\tcol = start_col + len;\n\t\t }\n\t\t}\n\t\tgot_tab = FALSE;\n\t\tnum_spaces = 0;\n\t }\n\t if (ptr[col] == NUL)\n\t\tbreak;\n\t vcol += chartabsize(ptr + col, (colnr_T)vcol);\n\t if (vcol >= MAXCOL)\n\t {\n\t\temsg_text_too_long();\n\t\tbreak;\n\t }\n\t if (has_mbyte)\n\t\tcol += (*mb_ptr2len)(ptr + col);\n\t else\n\t\t++col;\n\t}\n\tif (new_line == NULL)\t\t // out of memory\n\t break;\n\tline_breakcheck();\n }\n if (got_int)\n\temsg(_(e_interrupted));",
"#ifdef FEAT_VARTABS\n // If a single value was given then it can be considered equal to\n // either the value of 'tabstop' or the value of 'vartabstop'.\n if (tabstop_count(curbuf->b_p_vts_array) == 0\n\t&& tabstop_count(new_vts_array) == 1\n\t&& curbuf->b_p_ts == tabstop_first(new_vts_array))\n\t; // not changed\n else if (tabstop_count(curbuf->b_p_vts_array) > 0\n\t&& tabstop_eq(curbuf->b_p_vts_array, new_vts_array))\n\t; // not changed\n else\n\tredraw_curbuf_later(NOT_VALID);\n#else\n if (curbuf->b_p_ts != new_ts)\n\tredraw_curbuf_later(NOT_VALID);\n#endif\n if (first_line != 0)\n\tchanged_lines(first_line, 0, last_line + 1, 0L);",
" curwin->w_p_list = save_list;\t// restore 'list'",
"#ifdef FEAT_VARTABS\n if (new_ts_str != NULL)\t\t// set the new tabstop\n {\n\t// If 'vartabstop' is in use or if the value given to retab has more\n\t// than one tabstop then update 'vartabstop'.\n\tint *old_vts_ary = curbuf->b_p_vts_array;",
"\tif (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1)\n\t{\n\t set_string_option_direct((char_u *)\"vts\", -1, new_ts_str,\n\t\t\t\t\t\t\tOPT_FREE|OPT_LOCAL, 0);\n\t curbuf->b_p_vts_array = new_vts_array;\n\t vim_free(old_vts_ary);\n\t}\n\telse\n\t{\n\t // 'vartabstop' wasn't in use and a single value was given to\n\t // retab then update 'tabstop'.\n\t curbuf->b_p_ts = tabstop_first(new_vts_array);\n\t vim_free(new_vts_array);\n\t}\n\tvim_free(new_ts_str);\n }\n#else\n curbuf->b_p_ts = new_ts;\n#endif\n coladvance(curwin->w_curswant);",
" u_clearline();\n}",
"#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Get indent level from 'indentexpr'.\n */\n int\nget_expr_indent(void)\n{\n int\t\tindent = -1;\n char_u\t*inde_copy;\n pos_T\tsave_pos;\n colnr_T\tsave_curswant;\n int\t\tsave_set_curswant;\n int\t\tsave_State;\n int\t\tuse_sandbox = was_set_insecurely((char_u *)\"indentexpr\",\n\t\t\t\t\t\t\t\t OPT_LOCAL);\n sctx_T\tsave_sctx = current_sctx;",
" // Save and restore cursor position and curswant, in case it was changed\n // via :normal commands\n save_pos = curwin->w_cursor;\n save_curswant = curwin->w_curswant;\n save_set_curswant = curwin->w_set_curswant;\n set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);\n if (use_sandbox)\n\t++sandbox;\n ++textlock;\n current_sctx = curbuf->b_p_script_ctx[BV_INDE];",
" // Need to make a copy, the 'indentexpr' option could be changed while\n // evaluating it.\n inde_copy = vim_strsave(curbuf->b_p_inde);\n if (inde_copy != NULL)\n {\n\tindent = (int)eval_to_number(inde_copy);\n\tvim_free(inde_copy);\n }",
" if (use_sandbox)\n\t--sandbox;\n --textlock;\n current_sctx = save_sctx;",
" // Restore the cursor position so that 'indentexpr' doesn't need to.\n // Pretend to be in Insert mode, allow cursor past end of line for \"o\"\n // command.\n save_State = State;\n State = MODE_INSERT;\n curwin->w_cursor = save_pos;\n curwin->w_curswant = save_curswant;\n curwin->w_set_curswant = save_set_curswant;\n check_cursor();\n State = save_State;",
" // Reset did_throw, unless 'debug' has \"throw\" and inside a try/catch.\n if (did_throw && (vim_strchr(p_debug, 't') == NULL || trylevel == 0))\n {\n\thandle_did_throw();\n\tdid_throw = FALSE;\n }",
" // If there is an error, just keep the current indent.\n if (indent < 0)\n\tindent = get_indent();",
" return indent;\n}\n#endif",
" static int\nlisp_match(char_u *p)\n{\n char_u\tbuf[LSIZE];\n int\t\tlen;\n char_u\t*word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;",
" while (*word != NUL)\n {\n\t(void)copy_option_part(&word, buf, LSIZE, \",\");\n\tlen = (int)STRLEN(buf);\n\tif (STRNCMP(buf, p, len) == 0 && p[len] == ' ')\n\t return TRUE;\n }\n return FALSE;\n}",
"/*\n * When 'p' is present in 'cpoptions, a Vi compatible method is used.\n * The incompatible newer method is quite a bit better at indenting\n * code in lisp-like languages than the traditional one; it's still\n * mostly heuristics however -- Dirk van Deun, dirk@rave.org\n *\n * TODO:\n * Findmatch() should be adapted for lisp, also to make showmatch\n * work correctly: now (v5.3) it seems all C/C++ oriented:\n * - it does not recognize the #\\( and #\\) notations as character literals\n * - it doesn't know about comments starting with a semicolon\n * - it incorrectly interprets '(' as a character literal\n * All this messes up get_lisp_indent in some rare cases.\n * Update from Sergey Khorev:\n * I tried to fix the first two issues.\n */\n int\nget_lisp_indent(void)\n{\n pos_T\t*pos, realpos, paren;\n int\t\tamount;\n char_u\t*that;\n colnr_T\tcol;\n colnr_T\tfirsttry;\n int\t\tparencount, quotecount;\n int\t\tvi_lisp;",
" // Set vi_lisp to use the vi-compatible method\n vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);",
" realpos = curwin->w_cursor;\n curwin->w_cursor.col = 0;",
" if ((pos = findmatch(NULL, '(')) == NULL)\n\tpos = findmatch(NULL, '[');\n else\n {\n\tparen = *pos;\n\tpos = findmatch(NULL, '[');\n\tif (pos == NULL || LT_POSP(pos, &paren))\n\t pos = &paren;\n }\n if (pos != NULL)\n {\n\t// Extra trick: Take the indent of the first previous non-white\n\t// line that is at the same () level.\n\tamount = -1;\n\tparencount = 0;",
"\twhile (--curwin->w_cursor.lnum >= pos->lnum)\n\t{\n\t if (linewhite(curwin->w_cursor.lnum))\n\t\tcontinue;\n\t for (that = ml_get_curline(); *that != NUL; ++that)\n\t {\n\t\tif (*that == ';')\n\t\t{\n\t\t while (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t continue;\n\t\t}\n\t\tif (*that == '\\\\')\n\t\t{\n\t\t if (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t continue;\n\t\t}\n\t\tif (*that == '\"' && *(that + 1) != NUL)\n\t\t{\n\t\t while (*++that && *that != '\"')\n\t\t {\n\t\t\t// skipping escaped characters in the string\n\t\t\tif (*that == '\\\\')\n\t\t\t{\n\t\t\t if (*++that == NUL)\n\t\t\t\tbreak;\n\t\t\t if (that[1] == NUL)\n\t\t\t {\n\t\t\t\t++that;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t if (*that == NUL)\n\t\t\tbreak;\n\t\t}\n\t\tif (*that == '(' || *that == '[')\n\t\t ++parencount;\n\t\telse if (*that == ')' || *that == ']')\n\t\t --parencount;\n\t }\n\t if (parencount == 0)\n\t {\n\t\tamount = get_indent();\n\t\tbreak;\n\t }\n\t}",
"\tif (amount == -1)\n\t{\n\t curwin->w_cursor.lnum = pos->lnum;\n\t curwin->w_cursor.col = pos->col;\n\t col = pos->col;",
"\t that = ml_get_curline();",
"\t if (vi_lisp && get_indent() == 0)\n\t\tamount = 2;\n\t else\n\t {\n\t\tchar_u *line = that;",
"\t\tamount = 0;\n\t\twhile (*that && col)\n\t\t{\n\t\t amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);\n\t\t col--;\n\t\t}",
"\t\t// Some keywords require \"body\" indenting rules (the\n\t\t// non-standard-lisp ones are Scheme special forms):\n\t\t//\n\t\t// (let ((a 1)) instead (let ((a 1))\n\t\t// (...))\t of\t (...))",
"\t\tif (!vi_lisp && (*that == '(' || *that == '[')\n\t\t\t\t\t\t && lisp_match(that + 1))\n\t\t amount += 2;\n\t\telse\n\t\t{",
"\t\t that++;\n\t\t amount++;",
"\t\t firsttry = amount;",
"\t\t while (VIM_ISWHITE(*that))\n\t\t {\n\t\t\tamount += lbr_chartabsize(line, that, (colnr_T)amount);\n\t\t\t++that;\n\t\t }",
"\t\t if (*that && *that != ';') // not a comment line\n\t\t {\n\t\t\t// test *that != '(' to accommodate first let/do\n\t\t\t// argument if it is more than one line\n\t\t\tif (!vi_lisp && *that != '(' && *that != '[')\n\t\t\t firsttry++;",
"\t\t\tparencount = 0;\n\t\t\tquotecount = 0;",
"\t\t\tif (vi_lisp\n\t\t\t\t|| (*that != '\"'\n\t\t\t\t && *that != '\\''\n\t\t\t\t && *that != '#'\n\t\t\t\t && (*that < '0' || *that > '9')))\n\t\t\t{\n\t\t\t while (*that\n\t\t\t\t && (!VIM_ISWHITE(*that)\n\t\t\t\t\t|| quotecount\n\t\t\t\t\t|| parencount)\n\t\t\t\t && (!((*that == '(' || *that == '[')\n\t\t\t\t\t && !quotecount\n\t\t\t\t\t && !parencount\n\t\t\t\t\t && vi_lisp)))\n\t\t\t {\n\t\t\t\tif (*that == '\"')\n\t\t\t\t quotecount = !quotecount;\n\t\t\t\tif ((*that == '(' || *that == '[')\n\t\t\t\t\t\t\t && !quotecount)\n\t\t\t\t ++parencount;\n\t\t\t\tif ((*that == ')' || *that == ']')\n\t\t\t\t\t\t\t && !quotecount)\n\t\t\t\t --parencount;\n\t\t\t\tif (*that == '\\\\' && *(that+1) != NUL)\n\t\t\t\t amount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t\tamount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t }\n\t\t\t}\n\t\t\twhile (VIM_ISWHITE(*that))\n\t\t\t{\n\t\t\t amount += lbr_chartabsize(\n\t\t\t\t\t\t line, that, (colnr_T)amount);\n\t\t\t that++;\n\t\t\t}\n\t\t\tif (!*that || *that == ';')\n\t\t\t amount = firsttry;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n else\n\tamount = 0;\t// no matching '(' or '[' found, use zero indent",
" curwin->w_cursor = realpos;",
" return amount;\n}",
"/*\n * Re-indent the current line, based on the current contents of it and the\n * surrounding lines. Fixing the cursor position seems really easy -- I'm very\n * confused what all the part that handles Control-T is doing that I'm not.\n * \"get_the_indent\" should be get_c_indent, get_expr_indent or get_lisp_indent.\n */",
" void\nfixthisline(int (*get_the_indent)(void))\n{\n int amount = get_the_indent();",
" if (amount >= 0)\n {\n\tchange_indent(INDENT_SET, amount, FALSE, 0, TRUE);\n\tif (linewhite(curwin->w_cursor.lnum))\n\t did_ai = TRUE;\t// delete the indent if the line stays empty\n }\n}",
"/*\n * Fix indent for 'lisp' and 'cindent'.\n */\n void\nfix_indent(void)\n{\n if (p_paste)\n\treturn;\n if (curbuf->b_p_lisp && curbuf->b_p_ai)\n\tfixthisline(get_lisp_indent);\n else\n\tif (cindent_on())\n\t do_c_expr_indent();\n}",
"#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * \"indent()\" function\n */\n void\nf_indent(typval_T *argvars, typval_T *rettv)\n{\n linenr_T\tlnum;",
" if (in_vim9script() && check_for_lnum_arg(argvars, 0) == FAIL)\n\treturn;",
" lnum = tv_get_lnum(argvars);\n if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)\n\trettv->vval.v_number = get_indent_lnum(lnum);\n else\n {\n\tif (in_vim9script())\n\t semsg(_(e_invalid_line_number_nr), lnum);\n\trettv->vval.v_number = -1;\n }\n}",
"/*\n * \"lispindent(lnum)\" function\n */\n void\nf_lispindent(typval_T *argvars UNUSED, typval_T *rettv)\n{\n pos_T\tpos;\n linenr_T\tlnum;",
" if (in_vim9script() && check_for_lnum_arg(argvars, 0) == FAIL)\n\treturn;",
" pos = curwin->w_cursor;\n lnum = tv_get_lnum(argvars);\n if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)\n {\n\tcurwin->w_cursor.lnum = lnum;\n\trettv->vval.v_number = get_lisp_indent();\n\tcurwin->w_cursor = pos;\n }\n else if (in_vim9script())\n\tsemsg(_(e_invalid_line_number_nr), lnum);\n else\n\trettv->vval.v_number = -1;\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,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [2081, 87, 736], "buggy_code_start_loc": [2079, 1, 736], "filenames": ["src/indent.c", "src/testdir/test_lispwords.vim", "src/version.c"], "fixing_code_end_loc": [2084, 98, 739], "fixing_code_start_loc": [2079, 1, 737], "message": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "C88D3533-C1C8-4615-A2D5-30AC85BA943B", "versionEndExcluding": "8.2.5151", "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}, {"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": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Una Lectura Fuera de L\u00edmites en el repositorio de GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2183", "lastModified": "2023-05-03T12:15:46.177", "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-06-23T19:15:08.577", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d74ca3f9-380d-4c0a-b61c-11113cc98975"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GFD2A4YLBR7OIRHTL7CK6YNMEIQ264CN/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U743FMJGFQ35GBPCQ6OWMVZEJPDFVEWM/"}, {"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-125"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, "type": "CWE-125"}
| 319
|
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 * indent.c: Indentation related functions\n */",
"#include \"vim.h\"",
"#if defined(FEAT_VARTABS) || defined(PROTO)",
"/*\n * Set the integer values corresponding to the string setting of 'vartabstop'.\n * \"array\" will be set, caller must free it if needed.\n * Return FAIL for an error.\n */\n int\ntabstop_set(char_u *var, int **array)\n{\n int\t valcount = 1;\n int\t t;\n char_u *cp;",
" if (var[0] == NUL || (var[0] == '0' && var[1] == NUL))\n {\n\t*array = NULL;\n\treturn OK;\n }",
" for (cp = var; *cp != NUL; ++cp)\n {\n\tif (cp == var || cp[-1] == ',')\n\t{\n\t char_u *end;",
"\t if (strtol((char *)cp, (char **)&end, 10) <= 0)\n\t {\n\t\tif (cp != end)\n\t\t emsg(_(e_argument_must_be_positive));\n\t\telse\n\t\t semsg(_(e_invalid_argument_str), cp);\n\t\treturn FAIL;\n\t }\n\t}",
"\tif (VIM_ISDIGIT(*cp))\n\t continue;\n\tif (cp[0] == ',' && cp > var && cp[-1] != ',' && cp[1] != NUL)\n\t{\n\t ++valcount;\n\t continue;\n\t}\n\tsemsg(_(e_invalid_argument_str), var);\n\treturn FAIL;\n }",
" *array = ALLOC_MULT(int, valcount + 1);\n if (*array == NULL)\n\treturn FAIL;\n (*array)[0] = valcount;",
" t = 1;\n for (cp = var; *cp != NUL;)\n {\n\tint n = atoi((char *)cp);",
"\t// Catch negative values, overflow and ridiculous big values.\n\tif (n <= 0 || n > TABSTOP_MAX)\n\t{\n\t semsg(_(e_invalid_argument_str), cp);\n\t vim_free(*array);\n\t *array = NULL;\n\t return FAIL;\n\t}\n\t(*array)[t++] = n;\n\twhile (*cp != NUL && *cp != ',')\n\t ++cp;\n\tif (*cp != NUL)\n\t ++cp;\n }",
" return OK;\n}",
"/*\n * Calculate the number of screen spaces a tab will occupy.\n * If \"vts\" is set then the tab widths are taken from that array,\n * otherwise the value of ts is used.\n */\n int\ntabstop_padding(colnr_T col, int ts_arg, int *vts)\n{\n int\t\tts = ts_arg == 0 ? 8 : ts_arg;\n int\t\ttabcount;\n colnr_T\ttabcol = 0;\n int\t\tt;\n int\t\tpadding = 0;",
" if (vts == NULL || vts[0] == 0)\n\treturn ts - (col % ts);",
" tabcount = vts[0];",
" for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > col)\n\t{\n\t padding = (int)(tabcol - col);\n\t break;\n\t}\n }\n if (t > tabcount)\n\tpadding = vts[tabcount] - (int)((col - tabcol) % vts[tabcount]);",
" return padding;\n}",
"/*\n * Find the size of the tab that covers a particular column.\n */\n int\ntabstop_at(colnr_T col, int ts, int *vts)\n{\n int\t\ttabcount;\n colnr_T\ttabcol = 0;\n int\t\tt;\n int\t\ttab_size = 0;",
" if (vts == 0 || vts[0] == 0)\n\treturn ts;",
" tabcount = vts[0];\n for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > col)\n\t{\n\t tab_size = vts[t];\n\t break;\n\t}\n }\n if (t > tabcount)\n\ttab_size = vts[tabcount];",
" return tab_size;\n}",
"/*\n * Find the column on which a tab starts.\n */\n colnr_T\ntabstop_start(colnr_T col, int ts, int *vts)\n{\n int\t\ttabcount;\n colnr_T\ttabcol = 0;\n int\t\tt;\n int\t\texcess;",
" if (vts == NULL || vts[0] == 0)\n\treturn (col / ts) * ts;",
" tabcount = vts[0];\n for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > col)\n\t return tabcol - vts[t];\n }",
" excess = tabcol % vts[tabcount];\n return excess + ((col - excess) / vts[tabcount]) * vts[tabcount];\n}",
"/*\n * Find the number of tabs and spaces necessary to get from one column\n * to another.\n */\n void\ntabstop_fromto(\n\tcolnr_T start_col,\n\tcolnr_T end_col,\n\tint\tts_arg,\n\tint\t*vts,\n\tint\t*ntabs,\n\tint\t*nspcs)\n{\n int\t\tspaces = end_col - start_col;\n colnr_T\ttabcol = 0;\n int\t\tpadding = 0;\n int\t\ttabcount;\n int\t\tt;\n int\t\tts = ts_arg == 0 ? curbuf->b_p_ts : ts_arg;",
" if (vts == NULL || vts[0] == 0)\n {\n\tint tabs = 0;\n\tint initspc = 0;",
"\tinitspc = ts - (start_col % ts);\n\tif (spaces >= initspc)\n\t{\n\t spaces -= initspc;\n\t tabs++;\n\t}\n\ttabs += spaces / ts;\n\tspaces -= (spaces / ts) * ts;",
"\t*ntabs = tabs;\n\t*nspcs = spaces;\n\treturn;\n }",
" // Find the padding needed to reach the next tabstop.\n tabcount = vts[0];\n for (t = 1; t <= tabcount; ++t)\n {\n\ttabcol += vts[t];\n\tif (tabcol > start_col)\n\t{\n\t padding = (int)(tabcol - start_col);\n\t break;\n\t}\n }\n if (t > tabcount)\n\tpadding = vts[tabcount] - (int)((start_col - tabcol) % vts[tabcount]);",
" // If the space needed is less than the padding no tabs can be used.\n if (spaces < padding)\n {\n\t*ntabs = 0;\n\t*nspcs = spaces;\n\treturn;\n }",
" *ntabs = 1;\n spaces -= padding;",
" // At least one tab has been used. See if any more will fit.\n while (spaces != 0 && ++t <= tabcount)\n {\n\tpadding = vts[t];\n\tif (spaces < padding)\n\t{\n\t *nspcs = spaces;\n\t return;\n\t}\n\t++*ntabs;\n\tspaces -= padding;\n }",
" *ntabs += spaces / vts[tabcount];\n *nspcs = spaces % vts[tabcount];\n}",
"/*\n * See if two tabstop arrays contain the same values.\n */\n static int\ntabstop_eq(int *ts1, int *ts2)\n{\n int\t\tt;",
" if ((ts1 == 0 && ts2) || (ts1 && ts2 == 0))\n\treturn FALSE;\n if (ts1 == ts2)\n\treturn TRUE;\n if (ts1[0] != ts2[0])\n\treturn FALSE;",
" for (t = 1; t <= ts1[0]; ++t)\n\tif (ts1[t] != ts2[t])\n\t return FALSE;",
" return TRUE;\n}",
"# if defined(FEAT_BEVAL) || defined(PROTO)\n/*\n * Copy a tabstop array, allocating space for the new array.\n */\n int *\ntabstop_copy(int *oldts)\n{\n int\t\t*newts;\n int\t\tt;",
" if (oldts == NULL)\n\treturn NULL;\n newts = ALLOC_MULT(int, oldts[0] + 1);\n if (newts != NULL)\n\tfor (t = 0; t <= oldts[0]; ++t)\n\t newts[t] = oldts[t];\n return newts;\n}\n# endif",
"/*\n * Return a count of the number of tabstops.\n */\n int\ntabstop_count(int *ts)\n{\n return ts != NULL ? ts[0] : 0;\n}",
"/*\n * Return the first tabstop, or 8 if there are no tabstops defined.\n */\n int\ntabstop_first(int *ts)\n{\n return ts != NULL ? ts[1] : 8;\n}",
"#endif",
"/*\n * Return the effective shiftwidth value for current buffer, using the\n * 'tabstop' value when 'shiftwidth' is zero.\n */\n long\nget_sw_value(buf_T *buf)\n{\n return get_sw_value_col(buf, 0);\n}",
"/*\n * Idem, using \"pos\".\n */\n static long\nget_sw_value_pos(buf_T *buf, pos_T *pos)\n{\n pos_T save_cursor = curwin->w_cursor;\n long sw_value;",
" curwin->w_cursor = *pos;\n sw_value = get_sw_value_col(buf, get_nolist_virtcol());\n curwin->w_cursor = save_cursor;\n return sw_value;\n}",
"/*\n * Idem, using the first non-black in the current line.\n */\n long\nget_sw_value_indent(buf_T *buf)\n{\n pos_T pos = curwin->w_cursor;",
" pos.col = getwhitecols_curline();\n return get_sw_value_pos(buf, &pos);\n}",
"/*\n * Idem, using virtual column \"col\".\n */\n long\nget_sw_value_col(buf_T *buf, colnr_T col UNUSED)\n{\n return buf->b_p_sw ? buf->b_p_sw :\n#ifdef FEAT_VARTABS\n\ttabstop_at(col, buf->b_p_ts, buf->b_p_vts_array);\n#else\n\tbuf->b_p_ts;\n#endif\n}",
"/*\n * Return the effective softtabstop value for the current buffer, using the\n * 'shiftwidth' value when 'softtabstop' is negative.\n */\n long\nget_sts_value(void)\n{\n return curbuf->b_p_sts < 0 ? get_sw_value(curbuf) : curbuf->b_p_sts;\n}",
"/*\n * Count the size (in window cells) of the indent in the current line.\n */\n int\nget_indent(void)\n{\n#ifdef FEAT_VARTABS\n return get_indent_str_vtab(ml_get_curline(), (int)curbuf->b_p_ts,\n\t\t\t\t\t\t curbuf->b_p_vts_array, FALSE);\n#else\n return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts, FALSE);\n#endif\n}",
"/*\n * Count the size (in window cells) of the indent in line \"lnum\".\n */\n int\nget_indent_lnum(linenr_T lnum)\n{\n#ifdef FEAT_VARTABS\n return get_indent_str_vtab(ml_get(lnum), (int)curbuf->b_p_ts,\n\t\t\t\t\t\t curbuf->b_p_vts_array, FALSE);\n#else\n return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts, FALSE);\n#endif\n}",
"#if defined(FEAT_FOLDING) || defined(PROTO)\n/*\n * Count the size (in window cells) of the indent in line \"lnum\" of buffer\n * \"buf\".\n */\n int\nget_indent_buf(buf_T *buf, linenr_T lnum)\n{\n# ifdef FEAT_VARTABS\n return get_indent_str_vtab(ml_get_buf(buf, lnum, FALSE),\n\t\t\t (int)curbuf->b_p_ts, buf->b_p_vts_array, FALSE);\n# else\n return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts, FALSE);\n# endif\n}\n#endif",
"/*\n * count the size (in window cells) of the indent in line \"ptr\", with\n * 'tabstop' at \"ts\"\n */\n int\nget_indent_str(\n char_u\t*ptr,\n int\t\tts,\n int\t\tlist) // if TRUE, count only screen size for tabs\n{\n int\t\tcount = 0;",
" for ( ; *ptr; ++ptr)\n {\n\tif (*ptr == TAB)\n\t{\n\t if (!list || curwin->w_lcs_chars.tab1)\n\t\t// count a tab for what it is worth\n\t\tcount += ts - (count % ts);\n\t else\n\t\t// In list mode, when tab is not set, count screen char width\n\t\t// for Tab, displays: ^I\n\t\tcount += ptr2cells(ptr);\n\t}\n\telse if (*ptr == ' ')\n\t ++count;\t\t// count a space for one\n\telse\n\t break;\n }\n return count;\n}",
"#ifdef FEAT_VARTABS\n/*\n * Count the size (in window cells) of the indent in line \"ptr\", using\n * variable tabstops.\n * if \"list\" is TRUE, count only screen size for tabs.\n */\n int\nget_indent_str_vtab(char_u *ptr, int ts, int *vts, int list)\n{\n int\t\tcount = 0;",
" for ( ; *ptr; ++ptr)\n {\n\tif (*ptr == TAB) // count a tab for what it is worth\n\t{\n\t if (!list || curwin->w_lcs_chars.tab1)\n\t\tcount += tabstop_padding(count, ts, vts);\n\t else\n\t\t// In list mode, when tab is not set, count screen char width\n\t\t// for Tab, displays: ^I\n\t\tcount += ptr2cells(ptr);\n\t}\n\telse if (*ptr == ' ')\n\t ++count;\t\t// count a space for one\n\telse\n\t break;\n }\n return count;\n}\n#endif",
"/*\n * Set the indent of the current line.\n * Leaves the cursor on the first non-blank in the line.\n * Caller must take care of undo.\n * \"flags\":\n *\tSIN_CHANGED:\tcall changed_bytes() if the line was changed.\n *\tSIN_INSERT:\tinsert the indent in front of the line.\n *\tSIN_UNDO:\tsave line for undo before changing it.\n * Returns TRUE if the line was changed.\n */\n int\nset_indent(\n int\t\tsize,\t\t // measured in spaces\n int\t\tflags)\n{\n char_u\t*p;\n char_u\t*newline;\n char_u\t*oldline;\n char_u\t*s;\n int\t\ttodo;\n int\t\tind_len;\t // measured in characters\n int\t\tline_len;\n int\t\tdoit = FALSE;\n int\t\tind_done = 0;\t // measured in spaces\n#ifdef FEAT_VARTABS\n int\t\tind_col = 0;\n#endif\n int\t\ttab_pad;\n int\t\tretval = FALSE;\n int\t\torig_char_len = -1; // number of initial whitespace chars when\n\t\t\t\t // 'et' and 'pi' are both set",
" // First check if there is anything to do and compute the number of\n // characters needed for the indent.\n todo = size;\n ind_len = 0;\n p = oldline = ml_get_curline();",
" // Calculate the buffer size for the new indent, and check to see if it\n // isn't already set",
" // if 'expandtab' isn't set: use TABs; if both 'expandtab' and\n // 'preserveindent' are set count the number of characters at the\n // beginning of the line to be copied\n if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))\n {\n\t// If 'preserveindent' is set then reuse as much as possible of\n\t// the existing indent structure for the new indent\n\tif (!(flags & SIN_INSERT) && curbuf->b_p_pi)\n\t{\n\t ind_done = 0;",
"\t // count as many characters as we can use\n\t while (todo > 0 && VIM_ISWHITE(*p))\n\t {\n\t\tif (*p == TAB)\n\t\t{\n#ifdef FEAT_VARTABS\n\t\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t\t tab_pad = (int)curbuf->b_p_ts\n\t\t\t\t\t - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t\t // stop if this tab will overshoot the target\n\t\t if (todo < tab_pad)\n\t\t\tbreak;\n\t\t todo -= tab_pad;\n\t\t ++ind_len;\n\t\t ind_done += tab_pad;\n\t\t}\n\t\telse\n\t\t{\n\t\t --todo;\n\t\t ++ind_len;\n\t\t ++ind_done;\n\t\t}\n\t\t++p;\n\t }",
"#ifdef FEAT_VARTABS\n\t // These diverge from this point.\n\t ind_col = ind_done;\n#endif\n\t // Set initial number of whitespace chars to copy if we are\n\t // preserving indent but expandtab is set\n\t if (curbuf->b_p_et)\n\t\torig_char_len = ind_len;",
"\t // Fill to next tabstop with a tab, if possible\n#ifdef FEAT_VARTABS\n\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t if (todo >= tab_pad && orig_char_len == -1)\n\t {\n\t\tdoit = TRUE;\n\t\ttodo -= tab_pad;\n\t\t++ind_len;\n\t\t// ind_done += tab_pad;\n#ifdef FEAT_VARTABS\n\t\tind_col += tab_pad;\n#endif\n\t }\n\t}",
"\t// count tabs required for indent\n#ifdef FEAT_VARTABS\n\tfor (;;)\n\t{\n\t tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n\t if (todo < tab_pad)\n\t\tbreak;\n\t if (*p != TAB)\n\t\tdoit = TRUE;\n\t else\n\t\t++p;\n\t todo -= tab_pad;\n\t ++ind_len;\n\t ind_col += tab_pad;\n\t}\n#else\n\twhile (todo >= (int)curbuf->b_p_ts)\n\t{\n\t if (*p != TAB)\n\t\tdoit = TRUE;\n\t else\n\t\t++p;\n\t todo -= (int)curbuf->b_p_ts;\n\t ++ind_len;\n\t // ind_done += (int)curbuf->b_p_ts;\n\t}\n#endif\n }\n // count spaces required for indent\n while (todo > 0)\n {\n\tif (*p != ' ')\n\t doit = TRUE;\n\telse\n\t ++p;\n\t--todo;\n\t++ind_len;\n\t// ++ind_done;\n }",
" // Return if the indent is OK already.\n if (!doit && !VIM_ISWHITE(*p) && !(flags & SIN_INSERT))\n\treturn FALSE;",
" // Allocate memory for the new line.\n if (flags & SIN_INSERT)\n\tp = oldline;\n else\n\tp = skipwhite(p);\n line_len = (int)STRLEN(p) + 1;",
" // If 'preserveindent' and 'expandtab' are both set keep the original\n // characters and allocate accordingly. We will fill the rest with spaces\n // after the if (!curbuf->b_p_et) below.\n if (orig_char_len != -1)\n {\n\tnewline = alloc(orig_char_len + size - ind_done + line_len);\n\tif (newline == NULL)\n\t return FALSE;\n\ttodo = size - ind_done;\n\tind_len = orig_char_len + todo; // Set total length of indent in\n\t\t\t\t\t // characters, which may have been\n\t\t\t\t\t // undercounted until now\n\tp = oldline;\n\ts = newline;\n\twhile (orig_char_len > 0)\n\t{\n\t *s++ = *p++;\n\t orig_char_len--;\n\t}",
"\t// Skip over any additional white space (useful when newindent is less\n\t// than old)\n\twhile (VIM_ISWHITE(*p))\n\t ++p;",
" }\n else\n {\n\ttodo = size;\n\tnewline = alloc(ind_len + line_len);\n\tif (newline == NULL)\n\t return FALSE;\n\ts = newline;\n }",
" // Put the characters in the new line.\n // if 'expandtab' isn't set: use TABs\n if (!curbuf->b_p_et)\n {\n\t// If 'preserveindent' is set then reuse as much as possible of\n\t// the existing indent structure for the new indent\n\tif (!(flags & SIN_INSERT) && curbuf->b_p_pi)\n\t{\n\t p = oldline;\n\t ind_done = 0;",
"\t while (todo > 0 && VIM_ISWHITE(*p))\n\t {\n\t\tif (*p == TAB)\n\t\t{\n#ifdef FEAT_VARTABS\n\t\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t\t tab_pad = (int)curbuf->b_p_ts\n\t\t\t\t\t - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t\t // stop if this tab will overshoot the target\n\t\t if (todo < tab_pad)\n\t\t\tbreak;\n\t\t todo -= tab_pad;\n\t\t ind_done += tab_pad;\n\t\t}\n\t\telse\n\t\t{\n\t\t --todo;\n\t\t ++ind_done;\n\t\t}\n\t\t*s++ = *p++;\n\t }",
"\t // Fill to next tabstop with a tab, if possible\n#ifdef FEAT_VARTABS\n\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t if (todo >= tab_pad)\n\t {\n\t\t*s++ = TAB;\n\t\ttodo -= tab_pad;\n#ifdef FEAT_VARTABS\n\t\tind_done += tab_pad;\n#endif\n\t }",
"\t p = skipwhite(p);\n\t}",
"#ifdef FEAT_VARTABS\n\tfor (;;)\n\t{\n\t tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n\t if (todo < tab_pad)\n\t\tbreak;\n\t *s++ = TAB;\n\t todo -= tab_pad;\n\t ind_done += tab_pad;\n\t}\n#else\n\twhile (todo >= (int)curbuf->b_p_ts)\n\t{\n\t *s++ = TAB;\n\t todo -= (int)curbuf->b_p_ts;\n\t}\n#endif\n }\n while (todo > 0)\n {\n\t*s++ = ' ';\n\t--todo;\n }\n mch_memmove(s, p, (size_t)line_len);",
" // Replace the line (unless undo fails).\n if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)\n {\n\tcolnr_T old_offset = (colnr_T)(p - oldline);\n\tcolnr_T new_offset = (colnr_T)(s - newline);",
"\t// this may free \"newline\"\n\tml_replace(curwin->w_cursor.lnum, newline, FALSE);\n\tif (flags & SIN_CHANGED)\n\t changed_bytes(curwin->w_cursor.lnum, 0);",
"\t// Correct saved cursor position if it is in this line.\n\tif (saved_cursor.lnum == curwin->w_cursor.lnum)\n\t{\n\t if (saved_cursor.col >= old_offset)\n\t\t// cursor was after the indent, adjust for the number of\n\t\t// bytes added/removed\n\t\tsaved_cursor.col += ind_len - old_offset;\n\t else if (saved_cursor.col >= new_offset)\n\t\t// cursor was in the indent, and is now after it, put it back\n\t\t// at the start of the indent (replacing spaces with TAB)\n\t\tsaved_cursor.col = new_offset;\n\t}\n#ifdef FEAT_PROP_POPUP\n\t{\n\t int added = ind_len - old_offset;",
"\t // When increasing indent this behaves like spaces were inserted at\n\t // the old indent, when decreasing indent it behaves like spaces\n\t // were deleted at the new indent.\n\t adjust_prop_columns(curwin->w_cursor.lnum,\n\t\t\t added > 0 ? old_offset : (colnr_T)ind_len, added, 0);\n\t}\n#endif\n\tretval = TRUE;\n }\n else\n\tvim_free(newline);",
" curwin->w_cursor.col = ind_len;\n return retval;\n}",
"/*\n * Return the indent of the current line after a number. Return -1 if no\n * number was found. Used for 'n' in 'formatoptions': numbered list.\n * Since a pattern is used it can actually handle more than numbers.\n */\n int\nget_number_indent(linenr_T lnum)\n{\n colnr_T\tcol;\n pos_T\tpos;",
" regmatch_T\tregmatch;\n int\t\tlead_len = 0;\t// length of comment leader",
" if (lnum > curbuf->b_ml.ml_line_count)\n\treturn -1;\n pos.lnum = 0;",
" // In format_lines() (i.e. not insert mode), fo+=q is needed too...\n if ((State & MODE_INSERT) || has_format_option(FO_Q_COMS))\n\tlead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);",
" regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);\n if (regmatch.regprog != NULL)\n {\n\tregmatch.rm_ic = FALSE;",
"\t// vim_regexec() expects a pointer to a line. This lets us\n\t// start matching for the flp beyond any comment leader...\n\tif (vim_regexec(®match, ml_get(lnum) + lead_len, (colnr_T)0))\n\t{\n\t pos.lnum = lnum;\n\t pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));\n\t pos.coladd = 0;\n\t}\n\tvim_regfree(regmatch.regprog);\n }",
" if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)\n\treturn -1;\n getvcol(curwin, &pos, &col, NULL, NULL);\n return (int)col;\n}",
"#if defined(FEAT_LINEBREAK) || defined(PROTO)\n/*\n * This is called when 'breakindentopt' is changed and when a window is\n * initialized.\n */\n int\nbriopt_check(win_T *wp)\n{\n char_u\t*p;\n int\t\tbri_shift = 0;\n long\tbri_min = 20;\n int\t\tbri_sbr = FALSE;\n int\t\tbri_list = 0;\n int\t\tbri_vcol = 0;",
" p = wp->w_p_briopt;\n while (*p != NUL)\n {\n\tif (STRNCMP(p, \"shift:\", 6) == 0\n\t\t && ((p[6] == '-' && VIM_ISDIGIT(p[7])) || VIM_ISDIGIT(p[6])))\n\t{\n\t p += 6;\n\t bri_shift = getdigits(&p);\n\t}\n\telse if (STRNCMP(p, \"min:\", 4) == 0 && VIM_ISDIGIT(p[4]))\n\t{\n\t p += 4;\n\t bri_min = getdigits(&p);\n\t}\n\telse if (STRNCMP(p, \"sbr\", 3) == 0)\n\t{\n\t p += 3;\n\t bri_sbr = TRUE;\n\t}\n\telse if (STRNCMP(p, \"list:\", 5) == 0)\n\t{\n\t p += 5;\n\t bri_list = getdigits(&p);\n\t}\n\telse if (STRNCMP(p, \"column:\", 7) == 0)\n\t{\n\t p += 7;\n\t bri_vcol = getdigits(&p);\n\t}\n\tif (*p != ',' && *p != NUL)\n\t return FAIL;\n\tif (*p == ',')\n\t ++p;\n }",
" wp->w_briopt_shift = bri_shift;\n wp->w_briopt_min = bri_min;\n wp->w_briopt_sbr = bri_sbr;\n wp->w_briopt_list = bri_list;\n wp->w_briopt_vcol = bri_vcol;",
" return OK;\n}",
"/*\n * Return appropriate space number for breakindent, taking influencing\n * parameters into account. Window must be specified, since it is not\n * necessarily always the current one.\n */\n int\nget_breakindent_win(\n win_T\t*wp,\n char_u\t*line) // start of the line\n{\n static int\t prev_indent = 0;\t// cached indent value\n static long\t prev_ts = 0L;\t// cached tabstop value\n static char_u *prev_line = NULL;\t// cached pointer to line\n static varnumber_T prev_tick = 0; // changedtick of cached value\n# ifdef FEAT_VARTABS\n static int *prev_vts = NULL; // cached vartabs values\n# endif\n static int prev_list = 0;\t// cached list value\n static int prev_listopt = 0;\t// cached w_p_briopt_list value\n // cached formatlistpat value\n static char_u *prev_flp = NULL;\n int\t\t bri = 0;\n // window width minus window margin space, i.e. what rests for text\n const int\t eff_wwidth = wp->w_width\n\t\t\t - ((wp->w_p_nu || wp->w_p_rnu)\n\t\t\t\t&& (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)\n\t\t\t\t\t\t? number_width(wp) + 1 : 0);",
" // used cached indent, unless\n // - line pointer changed\n // - 'tabstop' changed\n // - 'briopt_list changed' changed or\n // - 'formatlistpattern' changed\n if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts\n\t || prev_tick != CHANGEDTICK(wp->w_buffer)\n\t || prev_listopt != wp->w_briopt_list\n\t || (prev_flp == NULL\n\t\t|| (STRCMP(prev_flp, get_flp_value(wp->w_buffer)) != 0))\n# ifdef FEAT_VARTABS\n\t || prev_vts != wp->w_buffer->b_p_vts_array\n# endif\n\t)\n {\n\tprev_line = line;\n\tprev_ts = wp->w_buffer->b_p_ts;\n\tprev_tick = CHANGEDTICK(wp->w_buffer);\n# ifdef FEAT_VARTABS\n\tprev_vts = wp->w_buffer->b_p_vts_array;\n\tif (wp->w_briopt_vcol == 0)\n\t prev_indent = get_indent_str_vtab(line,\n\t\t\t\t (int)wp->w_buffer->b_p_ts,\n\t\t\t\t wp->w_buffer->b_p_vts_array, wp->w_p_list);\n# else\n\tif (wp->w_briopt_vcol == 0)\n\t prev_indent = get_indent_str(line,\n\t\t\t\t (int)wp->w_buffer->b_p_ts, wp->w_p_list);\n# endif\n\tprev_listopt = wp->w_briopt_list;\n\tprev_list = 0;\n\tvim_free(prev_flp);\n\tprev_flp = vim_strsave(get_flp_value(wp->w_buffer));\n\t// add additional indent for numbered lists\n\tif (wp->w_briopt_list != 0 && wp->w_briopt_vcol == 0)\n\t{\n\t regmatch_T\t regmatch;",
"\t regmatch.regprog = vim_regcomp(prev_flp,\n\t\t\t\t RE_MAGIC + RE_STRING + RE_AUTO + RE_STRICT);",
"\t if (regmatch.regprog != NULL)\n\t {\n\t\tregmatch.rm_ic = FALSE;\n\t\tif (vim_regexec(®match, line, 0))\n\t\t{\n\t\t if (wp->w_briopt_list > 0)\n\t\t\tprev_list = wp->w_briopt_list;\n\t\t else\n\t\t\tprev_list = (*regmatch.endp - *regmatch.startp);\n\t\t}\n\t\tvim_regfree(regmatch.regprog);\n\t }\n\t}\n }\n if (wp->w_briopt_vcol != 0)\n {\n\t// column value has priority\n\tbri = wp->w_briopt_vcol;\n\tprev_list = 0;\n }\n else\n\tbri = prev_indent + wp->w_briopt_shift;",
" // Add offset for number column, if 'n' is in 'cpoptions'\n bri += win_col_off2(wp);",
" // add additional indent for numbered lists\n if (wp->w_briopt_list != 0)\n {\n\tif (wp->w_briopt_list > 0)\n\t bri += prev_list;\n\telse\n\t bri = prev_list;\n }",
" // indent minus the length of the showbreak string\n if (wp->w_briopt_sbr)\n\tbri -= vim_strsize(get_showbreak_value(wp));",
"\n // never indent past left window margin\n if (bri < 0)\n\tbri = 0;",
" // always leave at least bri_min characters on the left,\n // if text width is sufficient\n else if (bri > eff_wwidth - wp->w_briopt_min)\n\tbri = (eff_wwidth - wp->w_briopt_min < 0)\n\t\t\t\t\t ? 0 : eff_wwidth - wp->w_briopt_min;",
" return bri;\n}\n#endif",
"/*\n * When extra == 0: Return TRUE if the cursor is before or on the first\n *\t\t non-blank in the line.\n * When extra == 1: Return TRUE if the cursor is before the first non-blank in\n *\t\t the line.\n */\n int\ninindent(int extra)\n{\n char_u\t*ptr;\n colnr_T\tcol;",
" for (col = 0, ptr = ml_get_curline(); VIM_ISWHITE(*ptr); ++col)\n\t++ptr;\n if (col >= curwin->w_cursor.col + extra)\n\treturn TRUE;\n else\n\treturn FALSE;\n}",
"/*\n * op_reindent - handle reindenting a block of lines.\n */\n void\nop_reindent(oparg_T *oap, int (*how)(void))\n{\n long\ti = 0;\n char_u\t*l;\n int\t\tamount;\n linenr_T\tfirst_changed = 0;\n linenr_T\tlast_changed = 0;\n linenr_T\tstart_lnum = curwin->w_cursor.lnum;",
" // Don't even try when 'modifiable' is off.\n if (!curbuf->b_p_ma)\n {\n\temsg(_(e_cannot_make_changes_modifiable_is_off));\n\treturn;\n }",
" // Save for undo. Do this once for all lines, much faster than doing this\n // for each line separately, especially when undoing.\n if (u_savecommon(start_lnum - 1, start_lnum + oap->line_count,\n\t\t\t\t start_lnum + oap->line_count, FALSE) == OK)\n\tfor (i = oap->line_count; --i >= 0 && !got_int; )\n\t{\n\t // it's a slow thing to do, so give feedback so there's no worry\n\t // that the computer's just hung.",
"\t if (i > 1\n\t\t && (i % 50 == 0 || i == oap->line_count - 1)\n\t\t && oap->line_count > p_report)\n\t\tsmsg(_(\"%ld lines to indent... \"), i);",
"\t // Be vi-compatible: For lisp indenting the first line is not\n\t // indented, unless there is only one line.\n\t if (i != oap->line_count - 1 || oap->line_count == 1\n\t\t\t\t\t\t || how != get_lisp_indent)\n\t {\n\t\tl = skipwhite(ml_get_curline());\n\t\tif (*l == NUL)\t\t // empty or blank line\n\t\t amount = 0;\n\t\telse\n\t\t amount = how();\t // get the indent for this line",
"\t\tif (amount >= 0 && set_indent(amount, 0))\n\t\t{\n\t\t // did change the indent, call changed_lines() later\n\t\t if (first_changed == 0)\n\t\t\tfirst_changed = curwin->w_cursor.lnum;\n\t\t last_changed = curwin->w_cursor.lnum;\n\t\t}\n\t }\n\t ++curwin->w_cursor.lnum;\n\t curwin->w_cursor.col = 0; // make sure it's valid\n\t}",
" // put cursor on first non-blank of indented line\n curwin->w_cursor.lnum = start_lnum;\n beginline(BL_SOL | BL_FIX);",
" // Mark changed lines so that they will be redrawn. When Visual\n // highlighting was present, need to continue until the last line. When\n // there is no change still need to remove the Visual highlighting.\n if (last_changed != 0)\n\tchanged_lines(first_changed, 0,\n\t\toap->is_VIsual ? start_lnum + oap->line_count :\n\t\tlast_changed + 1, 0L);\n else if (oap->is_VIsual)\n\tredraw_curbuf_later(INVERTED);",
" if (oap->line_count > p_report)\n {\n\ti = oap->line_count - (i + 1);\n\tsmsg(NGETTEXT(\"%ld line indented \",\n\t\t\t\t\t\t \"%ld lines indented \", i), i);\n }\n if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)\n {\n\t// set '[ and '] marks\n\tcurbuf->b_op_start = oap->start;\n\tcurbuf->b_op_end = oap->end;\n }\n}",
"/*\n * Return TRUE if lines starting with '#' should be left aligned.\n */\n int\npreprocs_left(void)\n{\n return\n\t(curbuf->b_p_si && !curbuf->b_p_cin) ||\n\t(curbuf->b_p_cin && in_cinkeys('#', ' ', TRUE)\n\t\t\t\t\t && curbuf->b_ind_hash_comment == 0)\n\t;\n}",
"/*\n * Return TRUE if the conditions are OK for smart indenting.\n */\n int\nmay_do_si()\n{\n return curbuf->b_p_si\n\t&& !curbuf->b_p_cin\n# ifdef FEAT_EVAL\n\t&& *curbuf->b_p_inde == NUL\n# endif\n\t&& !p_paste;\n}",
"/*\n * Try to do some very smart auto-indenting.\n * Used when inserting a \"normal\" character.\n */\n void\nins_try_si(int c)\n{\n pos_T\t*pos, old_pos;\n char_u\t*ptr;\n int\t\ti;\n int\t\ttemp;",
" // do some very smart indenting when entering '{' or '}'\n if (((did_si || can_si_back) && c == '{')\n\t || (can_si && c == '}' && inindent(0)))\n {\n\t// for '}' set indent equal to indent of line containing matching '{'\n\tif (c == '}' && (pos = findmatch(NULL, '{')) != NULL)\n\t{\n\t old_pos = curwin->w_cursor;\n\t // If the matching '{' has a ')' immediately before it (ignoring\n\t // white-space), then line up with the start of the line\n\t // containing the matching '(' if there is one. This handles the\n\t // case where an \"if (..\\n..) {\" statement continues over multiple\n\t // lines -- webb\n\t ptr = ml_get(pos->lnum);\n\t i = pos->col;\n\t if (i > 0)\t\t// skip blanks before '{'\n\t\twhile (--i > 0 && VIM_ISWHITE(ptr[i]))\n\t\t ;\n\t curwin->w_cursor.lnum = pos->lnum;\n\t curwin->w_cursor.col = i;\n\t if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)\n\t\tcurwin->w_cursor = *pos;\n\t i = get_indent();\n\t curwin->w_cursor = old_pos;\n\t if (State & VREPLACE_FLAG)\n\t\tchange_indent(INDENT_SET, i, FALSE, NUL, TRUE);\n\t else\n\t\t(void)set_indent(i, SIN_CHANGED);\n\t}\n\telse if (curwin->w_cursor.col > 0)\n\t{\n\t // when inserting '{' after \"O\" reduce indent, but not\n\t // more than indent of previous line\n\t temp = TRUE;\n\t if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)\n\t {\n\t\told_pos = curwin->w_cursor;\n\t\ti = get_indent();\n\t\twhile (curwin->w_cursor.lnum > 1)\n\t\t{\n\t\t ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));",
"\t\t // ignore empty lines and lines starting with '#'.\n\t\t if (*ptr != '#' && *ptr != NUL)\n\t\t\tbreak;\n\t\t}\n\t\tif (get_indent() >= i)\n\t\t temp = FALSE;\n\t\tcurwin->w_cursor = old_pos;\n\t }\n\t if (temp)\n\t\tshift_line(TRUE, FALSE, 1, TRUE);\n\t}\n }",
" // set indent of '#' always to 0\n if (curwin->w_cursor.col > 0 && can_si && c == '#' && inindent(0))\n {\n\t// remember current indent for next line\n\told_indent = get_indent();\n\t(void)set_indent(0, SIN_CHANGED);\n }",
" // Adjust ai_col, the char at this position can be deleted.\n if (ai_col > curwin->w_cursor.col)\n\tai_col = curwin->w_cursor.col;\n}",
"/*\n * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).\n * Keep the cursor on the same character.\n * type == INDENT_INC\tincrease indent (for CTRL-T or <Tab>)\n * type == INDENT_DEC\tdecrease indent (for CTRL-D)\n * type == INDENT_SET\tset indent to \"amount\"\n * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).\n */\n void\nchange_indent(\n int\t\ttype,\n int\t\tamount,\n int\t\tround,\n int\t\treplaced,\t// replaced character, put on replace stack\n int\t\tcall_changed_bytes)\t// call changed_bytes()\n{\n int\t\tvcol;\n int\t\tlast_vcol;\n int\t\tinsstart_less;\t\t// reduction for Insstart.col\n int\t\tnew_cursor_col;\n int\t\ti;\n char_u\t*ptr;\n int\t\tsave_p_list;\n int\t\tstart_col;\n colnr_T\tvc;\n colnr_T\torig_col = 0;\t\t// init for GCC\n char_u\t*new_line, *orig_line = NULL;\t// init for GCC",
" // MODE_VREPLACE state needs to know what the line was like before changing\n if (State & VREPLACE_FLAG)\n {\n\torig_line = vim_strsave(ml_get_curline()); // Deal with NULL below\n\torig_col = curwin->w_cursor.col;\n }",
" // for the following tricks we don't want list mode\n save_p_list = curwin->w_p_list;\n curwin->w_p_list = FALSE;\n vc = getvcol_nolist(&curwin->w_cursor);\n vcol = vc;",
" // For Replace mode we need to fix the replace stack later, which is only\n // possible when the cursor is in the indent. Remember the number of\n // characters before the cursor if it's possible.\n start_col = curwin->w_cursor.col;",
" // determine offset from first non-blank\n new_cursor_col = curwin->w_cursor.col;\n beginline(BL_WHITE);\n new_cursor_col -= curwin->w_cursor.col;",
" insstart_less = curwin->w_cursor.col;",
" // If the cursor is in the indent, compute how many screen columns the\n // cursor is to the left of the first non-blank.\n if (new_cursor_col < 0)\n\tvcol = get_indent() - vcol;",
" if (new_cursor_col > 0)\t // can't fix replace stack\n\tstart_col = -1;",
" // Set the new indent. The cursor will be put on the first non-blank.\n if (type == INDENT_SET)\n\t(void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);\n else\n {\n\tint\tsave_State = State;",
"\t// Avoid being called recursively.\n\tif (State & VREPLACE_FLAG)\n\t State = MODE_INSERT;\n\tshift_line(type == INDENT_DEC, round, 1, call_changed_bytes);\n\tState = save_State;\n }\n insstart_less -= curwin->w_cursor.col;",
" // Try to put cursor on same character.\n // If the cursor is at or after the first non-blank in the line,\n // compute the cursor column relative to the column of the first\n // non-blank character.\n // If we are not in insert mode, leave the cursor on the first non-blank.\n // If the cursor is before the first non-blank, position it relative\n // to the first non-blank, counted in screen columns.\n if (new_cursor_col >= 0)\n {\n\t// When changing the indent while the cursor is touching it, reset\n\t// Insstart_col to 0.\n\tif (new_cursor_col == 0)\n\t insstart_less = MAXCOL;\n\tnew_cursor_col += curwin->w_cursor.col;\n }\n else if (!(State & MODE_INSERT))\n\tnew_cursor_col = curwin->w_cursor.col;\n else\n {\n\t// Compute the screen column where the cursor should be.\n\tvcol = get_indent() - vcol;\n\tcurwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);",
"\t// Advance the cursor until we reach the right screen column.\n\tvcol = last_vcol = 0;\n\tnew_cursor_col = -1;\n\tptr = ml_get_curline();\n\twhile (vcol <= (int)curwin->w_virtcol)\n\t{\n\t last_vcol = vcol;\n\t if (has_mbyte && new_cursor_col >= 0)\n\t\tnew_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);\n\t else\n\t\t++new_cursor_col;\n\t if (ptr[new_cursor_col] == NUL)\n\t\tbreak;\n\t vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol);\n\t}\n\tvcol = last_vcol;",
"\t// May need to insert spaces to be able to position the cursor on\n\t// the right screen column.\n\tif (vcol != (int)curwin->w_virtcol)\n\t{\n\t curwin->w_cursor.col = (colnr_T)new_cursor_col;\n\t i = (int)curwin->w_virtcol - vcol;\n\t ptr = alloc(i + 1);\n\t if (ptr != NULL)\n\t {\n\t\tnew_cursor_col += i;\n\t\tptr[i] = NUL;\n\t\twhile (--i >= 0)\n\t\t ptr[i] = ' ';\n\t\tins_str(ptr);\n\t\tvim_free(ptr);\n\t }\n\t}",
"\t// When changing the indent while the cursor is in it, reset\n\t// Insstart_col to 0.\n\tinsstart_less = MAXCOL;\n }",
" curwin->w_p_list = save_p_list;",
" if (new_cursor_col <= 0)\n\tcurwin->w_cursor.col = 0;\n else\n\tcurwin->w_cursor.col = (colnr_T)new_cursor_col;\n curwin->w_set_curswant = TRUE;\n changed_cline_bef_curs();",
" // May have to adjust the start of the insert.\n if (State & MODE_INSERT)\n {\n\tif (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)\n\t{\n\t if ((int)Insstart.col <= insstart_less)\n\t\tInsstart.col = 0;\n\t else\n\t\tInsstart.col -= insstart_less;\n\t}\n\tif ((int)ai_col <= insstart_less)\n\t ai_col = 0;\n\telse\n\t ai_col -= insstart_less;\n }",
" // For MODE_REPLACE state, may have to fix the replace stack, if it's\n // possible. If the number of characters before the cursor decreased, need\n // to pop a few characters from the replace stack.\n // If the number of characters before the cursor increased, need to push a\n // few NULs onto the replace stack.\n if (REPLACE_NORMAL(State) && start_col >= 0)\n {\n\twhile (start_col > (int)curwin->w_cursor.col)\n\t{\n\t replace_join(0);\t // remove a NUL from the replace stack\n\t --start_col;\n\t}\n\twhile (start_col < (int)curwin->w_cursor.col || replaced)\n\t{\n\t replace_push(NUL);\n\t if (replaced)\n\t {\n\t\treplace_push(replaced);\n\t\treplaced = NUL;\n\t }\n\t ++start_col;\n\t}\n }",
" // For MODE_VREPLACE state, we also have to fix the replace stack. In this\n // case it is always possible because we backspace over the whole line and\n // then put it back again the way we wanted it.\n if (State & VREPLACE_FLAG)\n {\n\t// If orig_line didn't allocate, just return. At least we did the job,\n\t// even if you can't backspace.\n\tif (orig_line == NULL)\n\t return;",
"\t// Save new line\n\tnew_line = vim_strsave(ml_get_curline());\n\tif (new_line == NULL)\n\t return;",
"\t// We only put back the new line up to the cursor\n\tnew_line[curwin->w_cursor.col] = NUL;",
"\t// Put back original line\n\tml_replace(curwin->w_cursor.lnum, orig_line, FALSE);\n\tcurwin->w_cursor.col = orig_col;",
"\t// Backspace from cursor to start of line\n\tbackspace_until_column(0);",
"\t// Insert new stuff into line again\n\tins_bytes(new_line);",
"\tvim_free(new_line);\n }\n}",
"/*\n * Copy the indent from ptr to the current line (and fill to size)\n * Leaves the cursor on the first non-blank in the line.\n * Returns TRUE if the line was changed.\n */\n int\ncopy_indent(int size, char_u *src)\n{\n char_u\t*p = NULL;\n char_u\t*line = NULL;\n char_u\t*s;\n int\t\ttodo;\n int\t\tind_len;\n int\t\tline_len = 0;\n int\t\ttab_pad;\n int\t\tind_done;\n int\t\tround;\n#ifdef FEAT_VARTABS\n int\t\tind_col;\n#endif",
" // Round 1: compute the number of characters needed for the indent\n // Round 2: copy the characters.\n for (round = 1; round <= 2; ++round)\n {\n\ttodo = size;\n\tind_len = 0;\n\tind_done = 0;\n#ifdef FEAT_VARTABS\n\tind_col = 0;\n#endif\n\ts = src;",
"\t// Count/copy the usable portion of the source line\n\twhile (todo > 0 && VIM_ISWHITE(*s))\n\t{\n\t if (*s == TAB)\n\t {\n#ifdef FEAT_VARTABS\n\t\ttab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\t\ttab_pad = (int)curbuf->b_p_ts\n\t\t\t\t\t - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\t\t// Stop if this tab will overshoot the target\n\t\tif (todo < tab_pad)\n\t\t break;\n\t\ttodo -= tab_pad;\n\t\tind_done += tab_pad;\n#ifdef FEAT_VARTABS\n\t\tind_col += tab_pad;\n#endif\n\t }\n\t else\n\t {\n\t\t--todo;\n\t\t++ind_done;\n#ifdef FEAT_VARTABS\n\t\t++ind_col;\n#endif\n\t }\n\t ++ind_len;\n\t if (p != NULL)\n\t\t*p++ = *s;\n\t ++s;\n\t}",
"\t// Fill to next tabstop with a tab, if possible\n#ifdef FEAT_VARTABS\n\ttab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n#else\n\ttab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);\n#endif\n\tif (todo >= tab_pad && !curbuf->b_p_et)\n\t{\n\t todo -= tab_pad;\n\t ++ind_len;\n#ifdef FEAT_VARTABS\n\t ind_col += tab_pad;\n#endif\n\t if (p != NULL)\n\t\t*p++ = TAB;\n\t}",
"\t// Add tabs required for indent\n\tif (!curbuf->b_p_et)\n\t{\n#ifdef FEAT_VARTABS\n\t for (;;)\n\t {\n\t\ttab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,\n\t\t\t\t\t\t\tcurbuf->b_p_vts_array);\n\t\tif (todo < tab_pad)\n\t\t break;\n\t\ttodo -= tab_pad;\n\t\t++ind_len;\n\t\tind_col += tab_pad;\n\t\tif (p != NULL)\n\t\t *p++ = TAB;\n\t }\n#else\n\t while (todo >= (int)curbuf->b_p_ts)\n\t {\n\t\ttodo -= (int)curbuf->b_p_ts;\n\t\t++ind_len;\n\t\tif (p != NULL)\n\t\t *p++ = TAB;\n\t }\n#endif\n\t}",
"\t// Count/add spaces required for indent\n\twhile (todo > 0)\n\t{\n\t --todo;\n\t ++ind_len;\n\t if (p != NULL)\n\t\t*p++ = ' ';\n\t}",
"\tif (p == NULL)\n\t{\n\t // Allocate memory for the result: the copied indent, new indent\n\t // and the rest of the line.\n\t line_len = (int)STRLEN(ml_get_curline()) + 1;\n\t line = alloc(ind_len + line_len);\n\t if (line == NULL)\n\t\treturn FALSE;\n\t p = line;\n\t}\n }",
" // Append the original line\n mch_memmove(p, ml_get_curline(), (size_t)line_len);",
" // Replace the line\n ml_replace(curwin->w_cursor.lnum, line, FALSE);",
" // Put the cursor after the indent.\n curwin->w_cursor.col = ind_len;\n return TRUE;\n}",
"/*\n * Give a \"resulting text too long\" error and maybe set got_int.\n */\n static void\nemsg_text_too_long(void)\n{\n emsg(_(e_resulting_text_too_long));\n#ifdef FEAT_EVAL\n // when not inside a try/catch set got_int to break out of any loop\n if (trylevel == 0)\n#endif\n\tgot_int = TRUE;\n}",
"/*\n * \":retab\".\n */\n void\nex_retab(exarg_T *eap)\n{\n linenr_T\tlnum;\n int\t\tgot_tab = FALSE;\n long\tnum_spaces = 0;\n long\tnum_tabs;\n long\tlen;\n long\tcol;\n long\tvcol;\n long\tstart_col = 0;\t\t// For start of white-space string\n long\tstart_vcol = 0;\t\t// For start of white-space string\n long\told_len;\n long\tnew_len;\n char_u\t*ptr;\n char_u\t*new_line = (char_u *)1; // init to non-NULL\n int\t\tdid_undo;\t\t// called u_save for current line\n#ifdef FEAT_VARTABS\n int\t\t*new_vts_array = NULL;\n char_u\t*new_ts_str;\t\t// string value of tab argument\n#else\n int\t\ttemp;\n int\t\tnew_ts;\n#endif\n int\t\tsave_list;\n linenr_T\tfirst_line = 0;\t\t// first changed line\n linenr_T\tlast_line = 0;\t\t// last changed line",
" save_list = curwin->w_p_list;\n curwin->w_p_list = 0;\t // don't want list mode here",
"#ifdef FEAT_VARTABS\n new_ts_str = eap->arg;\n if (tabstop_set(eap->arg, &new_vts_array) == FAIL)\n\treturn;\n while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')\n\t++(eap->arg);",
" // This ensures that either new_vts_array and new_ts_str are freshly\n // allocated, or new_vts_array points to an existing array and new_ts_str\n // is null.\n if (new_vts_array == NULL)\n {\n\tnew_vts_array = curbuf->b_p_vts_array;\n\tnew_ts_str = NULL;\n }\n else\n\tnew_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str);\n#else\n ptr = eap->arg;\n new_ts = getdigits(&ptr);\n if (new_ts < 0 && *eap->arg == '-')\n {\n\temsg(_(e_argument_must_be_positive));\n\treturn;\n }\n if (new_ts < 0 || new_ts > TABSTOP_MAX)\n {\n\tsemsg(_(e_invalid_argument_str), eap->arg);\n\treturn;\n }\n if (new_ts == 0)\n\tnew_ts = curbuf->b_p_ts;\n#endif\n for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)\n {\n\tptr = ml_get(lnum);\n\tcol = 0;\n\tvcol = 0;\n\tdid_undo = FALSE;\n\tfor (;;)\n\t{\n\t if (VIM_ISWHITE(ptr[col]))\n\t {\n\t\tif (!got_tab && num_spaces == 0)\n\t\t{\n\t\t // First consecutive white-space\n\t\t start_vcol = vcol;\n\t\t start_col = col;\n\t\t}\n\t\tif (ptr[col] == ' ')\n\t\t num_spaces++;\n\t\telse\n\t\t got_tab = TRUE;\n\t }\n\t else\n\t {\n\t\tif (got_tab || (eap->forceit && num_spaces > 1))\n\t\t{\n\t\t // Retabulate this string of white-space",
"\t\t // len is virtual length of white string\n\t\t len = num_spaces = vcol - start_vcol;\n\t\t num_tabs = 0;\n\t\t if (!curbuf->b_p_et)\n\t\t {\n#ifdef FEAT_VARTABS\n\t\t\tint t, s;",
"\t\t\ttabstop_fromto(start_vcol, vcol,\n\t\t\t\t\tcurbuf->b_p_ts, new_vts_array, &t, &s);\n\t\t\tnum_tabs = t;\n\t\t\tnum_spaces = s;\n#else\n\t\t\ttemp = new_ts - (start_vcol % new_ts);\n\t\t\tif (num_spaces >= temp)\n\t\t\t{\n\t\t\t num_spaces -= temp;\n\t\t\t num_tabs++;\n\t\t\t}\n\t\t\tnum_tabs += num_spaces / new_ts;\n\t\t\tnum_spaces -= (num_spaces / new_ts) * new_ts;\n#endif\n\t\t }\n\t\t if (curbuf->b_p_et || got_tab ||\n\t\t\t\t\t(num_spaces + num_tabs < len))\n\t\t {\n\t\t\tif (did_undo == FALSE)\n\t\t\t{\n\t\t\t did_undo = TRUE;\n\t\t\t if (u_save((linenr_T)(lnum - 1),\n\t\t\t\t\t\t(linenr_T)(lnum + 1)) == FAIL)\n\t\t\t {\n\t\t\t\tnew_line = NULL;\t// flag out-of-memory\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}",
"\t\t\t// len is actual number of white characters used\n\t\t\tlen = num_spaces + num_tabs;\n\t\t\told_len = (long)STRLEN(ptr);\n\t\t\tnew_len = old_len - col + start_col + len + 1;\n\t\t\tif (new_len <= 0 || new_len >= MAXCOL)\n\t\t\t{\n\t\t\t emsg_text_too_long();\n\t\t\t break;\n\t\t\t}\n\t\t\tnew_line = alloc(new_len);\n\t\t\tif (new_line == NULL)\n\t\t\t break;\n\t\t\tif (start_col > 0)\n\t\t\t mch_memmove(new_line, ptr, (size_t)start_col);\n\t\t\tmch_memmove(new_line + start_col + len,\n\t\t\t\t ptr + col, (size_t)(old_len - col + 1));\n\t\t\tptr = new_line + start_col;\n\t\t\tfor (col = 0; col < len; col++)\n\t\t\t ptr[col] = (col < num_tabs) ? '\\t' : ' ';\n\t\t\tif (ml_replace(lnum, new_line, FALSE) == OK)\n\t\t\t // \"new_line\" may have been copied\n\t\t\t new_line = curbuf->b_ml.ml_line_ptr;\n\t\t\tif (first_line == 0)\n\t\t\t first_line = lnum;\n\t\t\tlast_line = lnum;\n\t\t\tptr = new_line;\n\t\t\tcol = start_col + len;\n\t\t }\n\t\t}\n\t\tgot_tab = FALSE;\n\t\tnum_spaces = 0;\n\t }\n\t if (ptr[col] == NUL)\n\t\tbreak;\n\t vcol += chartabsize(ptr + col, (colnr_T)vcol);\n\t if (vcol >= MAXCOL)\n\t {\n\t\temsg_text_too_long();\n\t\tbreak;\n\t }\n\t if (has_mbyte)\n\t\tcol += (*mb_ptr2len)(ptr + col);\n\t else\n\t\t++col;\n\t}\n\tif (new_line == NULL)\t\t // out of memory\n\t break;\n\tline_breakcheck();\n }\n if (got_int)\n\temsg(_(e_interrupted));",
"#ifdef FEAT_VARTABS\n // If a single value was given then it can be considered equal to\n // either the value of 'tabstop' or the value of 'vartabstop'.\n if (tabstop_count(curbuf->b_p_vts_array) == 0\n\t&& tabstop_count(new_vts_array) == 1\n\t&& curbuf->b_p_ts == tabstop_first(new_vts_array))\n\t; // not changed\n else if (tabstop_count(curbuf->b_p_vts_array) > 0\n\t&& tabstop_eq(curbuf->b_p_vts_array, new_vts_array))\n\t; // not changed\n else\n\tredraw_curbuf_later(NOT_VALID);\n#else\n if (curbuf->b_p_ts != new_ts)\n\tredraw_curbuf_later(NOT_VALID);\n#endif\n if (first_line != 0)\n\tchanged_lines(first_line, 0, last_line + 1, 0L);",
" curwin->w_p_list = save_list;\t// restore 'list'",
"#ifdef FEAT_VARTABS\n if (new_ts_str != NULL)\t\t// set the new tabstop\n {\n\t// If 'vartabstop' is in use or if the value given to retab has more\n\t// than one tabstop then update 'vartabstop'.\n\tint *old_vts_ary = curbuf->b_p_vts_array;",
"\tif (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1)\n\t{\n\t set_string_option_direct((char_u *)\"vts\", -1, new_ts_str,\n\t\t\t\t\t\t\tOPT_FREE|OPT_LOCAL, 0);\n\t curbuf->b_p_vts_array = new_vts_array;\n\t vim_free(old_vts_ary);\n\t}\n\telse\n\t{\n\t // 'vartabstop' wasn't in use and a single value was given to\n\t // retab then update 'tabstop'.\n\t curbuf->b_p_ts = tabstop_first(new_vts_array);\n\t vim_free(new_vts_array);\n\t}\n\tvim_free(new_ts_str);\n }\n#else\n curbuf->b_p_ts = new_ts;\n#endif\n coladvance(curwin->w_curswant);",
" u_clearline();\n}",
"#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Get indent level from 'indentexpr'.\n */\n int\nget_expr_indent(void)\n{\n int\t\tindent = -1;\n char_u\t*inde_copy;\n pos_T\tsave_pos;\n colnr_T\tsave_curswant;\n int\t\tsave_set_curswant;\n int\t\tsave_State;\n int\t\tuse_sandbox = was_set_insecurely((char_u *)\"indentexpr\",\n\t\t\t\t\t\t\t\t OPT_LOCAL);\n sctx_T\tsave_sctx = current_sctx;",
" // Save and restore cursor position and curswant, in case it was changed\n // via :normal commands\n save_pos = curwin->w_cursor;\n save_curswant = curwin->w_curswant;\n save_set_curswant = curwin->w_set_curswant;\n set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);\n if (use_sandbox)\n\t++sandbox;\n ++textlock;\n current_sctx = curbuf->b_p_script_ctx[BV_INDE];",
" // Need to make a copy, the 'indentexpr' option could be changed while\n // evaluating it.\n inde_copy = vim_strsave(curbuf->b_p_inde);\n if (inde_copy != NULL)\n {\n\tindent = (int)eval_to_number(inde_copy);\n\tvim_free(inde_copy);\n }",
" if (use_sandbox)\n\t--sandbox;\n --textlock;\n current_sctx = save_sctx;",
" // Restore the cursor position so that 'indentexpr' doesn't need to.\n // Pretend to be in Insert mode, allow cursor past end of line for \"o\"\n // command.\n save_State = State;\n State = MODE_INSERT;\n curwin->w_cursor = save_pos;\n curwin->w_curswant = save_curswant;\n curwin->w_set_curswant = save_set_curswant;\n check_cursor();\n State = save_State;",
" // Reset did_throw, unless 'debug' has \"throw\" and inside a try/catch.\n if (did_throw && (vim_strchr(p_debug, 't') == NULL || trylevel == 0))\n {\n\thandle_did_throw();\n\tdid_throw = FALSE;\n }",
" // If there is an error, just keep the current indent.\n if (indent < 0)\n\tindent = get_indent();",
" return indent;\n}\n#endif",
" static int\nlisp_match(char_u *p)\n{\n char_u\tbuf[LSIZE];\n int\t\tlen;\n char_u\t*word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;",
" while (*word != NUL)\n {\n\t(void)copy_option_part(&word, buf, LSIZE, \",\");\n\tlen = (int)STRLEN(buf);\n\tif (STRNCMP(buf, p, len) == 0 && p[len] == ' ')\n\t return TRUE;\n }\n return FALSE;\n}",
"/*\n * When 'p' is present in 'cpoptions, a Vi compatible method is used.\n * The incompatible newer method is quite a bit better at indenting\n * code in lisp-like languages than the traditional one; it's still\n * mostly heuristics however -- Dirk van Deun, dirk@rave.org\n *\n * TODO:\n * Findmatch() should be adapted for lisp, also to make showmatch\n * work correctly: now (v5.3) it seems all C/C++ oriented:\n * - it does not recognize the #\\( and #\\) notations as character literals\n * - it doesn't know about comments starting with a semicolon\n * - it incorrectly interprets '(' as a character literal\n * All this messes up get_lisp_indent in some rare cases.\n * Update from Sergey Khorev:\n * I tried to fix the first two issues.\n */\n int\nget_lisp_indent(void)\n{\n pos_T\t*pos, realpos, paren;\n int\t\tamount;\n char_u\t*that;\n colnr_T\tcol;\n colnr_T\tfirsttry;\n int\t\tparencount, quotecount;\n int\t\tvi_lisp;",
" // Set vi_lisp to use the vi-compatible method\n vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);",
" realpos = curwin->w_cursor;\n curwin->w_cursor.col = 0;",
" if ((pos = findmatch(NULL, '(')) == NULL)\n\tpos = findmatch(NULL, '[');\n else\n {\n\tparen = *pos;\n\tpos = findmatch(NULL, '[');\n\tif (pos == NULL || LT_POSP(pos, &paren))\n\t pos = &paren;\n }\n if (pos != NULL)\n {\n\t// Extra trick: Take the indent of the first previous non-white\n\t// line that is at the same () level.\n\tamount = -1;\n\tparencount = 0;",
"\twhile (--curwin->w_cursor.lnum >= pos->lnum)\n\t{\n\t if (linewhite(curwin->w_cursor.lnum))\n\t\tcontinue;\n\t for (that = ml_get_curline(); *that != NUL; ++that)\n\t {\n\t\tif (*that == ';')\n\t\t{\n\t\t while (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t continue;\n\t\t}\n\t\tif (*that == '\\\\')\n\t\t{\n\t\t if (*(that + 1) != NUL)\n\t\t\t++that;\n\t\t continue;\n\t\t}\n\t\tif (*that == '\"' && *(that + 1) != NUL)\n\t\t{\n\t\t while (*++that && *that != '\"')\n\t\t {\n\t\t\t// skipping escaped characters in the string\n\t\t\tif (*that == '\\\\')\n\t\t\t{\n\t\t\t if (*++that == NUL)\n\t\t\t\tbreak;\n\t\t\t if (that[1] == NUL)\n\t\t\t {\n\t\t\t\t++that;\n\t\t\t\tbreak;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t if (*that == NUL)\n\t\t\tbreak;\n\t\t}\n\t\tif (*that == '(' || *that == '[')\n\t\t ++parencount;\n\t\telse if (*that == ')' || *that == ']')\n\t\t --parencount;\n\t }\n\t if (parencount == 0)\n\t {\n\t\tamount = get_indent();\n\t\tbreak;\n\t }\n\t}",
"\tif (amount == -1)\n\t{\n\t curwin->w_cursor.lnum = pos->lnum;\n\t curwin->w_cursor.col = pos->col;\n\t col = pos->col;",
"\t that = ml_get_curline();",
"\t if (vi_lisp && get_indent() == 0)\n\t\tamount = 2;\n\t else\n\t {\n\t\tchar_u *line = that;",
"\t\tamount = 0;\n\t\twhile (*that && col)\n\t\t{\n\t\t amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);\n\t\t col--;\n\t\t}",
"\t\t// Some keywords require \"body\" indenting rules (the\n\t\t// non-standard-lisp ones are Scheme special forms):\n\t\t//\n\t\t// (let ((a 1)) instead (let ((a 1))\n\t\t// (...))\t of\t (...))",
"\t\tif (!vi_lisp && (*that == '(' || *that == '[')\n\t\t\t\t\t\t && lisp_match(that + 1))\n\t\t amount += 2;\n\t\telse\n\t\t{",
"\t\t if (*that != NUL)\n\t\t {\n\t\t\tthat++;\n\t\t\tamount++;\n\t\t }",
"\t\t firsttry = amount;",
"\t\t while (VIM_ISWHITE(*that))\n\t\t {\n\t\t\tamount += lbr_chartabsize(line, that, (colnr_T)amount);\n\t\t\t++that;\n\t\t }",
"\t\t if (*that && *that != ';') // not a comment line\n\t\t {\n\t\t\t// test *that != '(' to accommodate first let/do\n\t\t\t// argument if it is more than one line\n\t\t\tif (!vi_lisp && *that != '(' && *that != '[')\n\t\t\t firsttry++;",
"\t\t\tparencount = 0;\n\t\t\tquotecount = 0;",
"\t\t\tif (vi_lisp\n\t\t\t\t|| (*that != '\"'\n\t\t\t\t && *that != '\\''\n\t\t\t\t && *that != '#'\n\t\t\t\t && (*that < '0' || *that > '9')))\n\t\t\t{\n\t\t\t while (*that\n\t\t\t\t && (!VIM_ISWHITE(*that)\n\t\t\t\t\t|| quotecount\n\t\t\t\t\t|| parencount)\n\t\t\t\t && (!((*that == '(' || *that == '[')\n\t\t\t\t\t && !quotecount\n\t\t\t\t\t && !parencount\n\t\t\t\t\t && vi_lisp)))\n\t\t\t {\n\t\t\t\tif (*that == '\"')\n\t\t\t\t quotecount = !quotecount;\n\t\t\t\tif ((*that == '(' || *that == '[')\n\t\t\t\t\t\t\t && !quotecount)\n\t\t\t\t ++parencount;\n\t\t\t\tif ((*that == ')' || *that == ']')\n\t\t\t\t\t\t\t && !quotecount)\n\t\t\t\t --parencount;\n\t\t\t\tif (*that == '\\\\' && *(that+1) != NUL)\n\t\t\t\t amount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t\tamount += lbr_chartabsize_adv(\n\t\t\t\t\t\tline, &that, (colnr_T)amount);\n\t\t\t }\n\t\t\t}\n\t\t\twhile (VIM_ISWHITE(*that))\n\t\t\t{\n\t\t\t amount += lbr_chartabsize(\n\t\t\t\t\t\t line, that, (colnr_T)amount);\n\t\t\t that++;\n\t\t\t}\n\t\t\tif (!*that || *that == ';')\n\t\t\t amount = firsttry;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n else\n\tamount = 0;\t// no matching '(' or '[' found, use zero indent",
" curwin->w_cursor = realpos;",
" return amount;\n}",
"/*\n * Re-indent the current line, based on the current contents of it and the\n * surrounding lines. Fixing the cursor position seems really easy -- I'm very\n * confused what all the part that handles Control-T is doing that I'm not.\n * \"get_the_indent\" should be get_c_indent, get_expr_indent or get_lisp_indent.\n */",
" void\nfixthisline(int (*get_the_indent)(void))\n{\n int amount = get_the_indent();",
" if (amount >= 0)\n {\n\tchange_indent(INDENT_SET, amount, FALSE, 0, TRUE);\n\tif (linewhite(curwin->w_cursor.lnum))\n\t did_ai = TRUE;\t// delete the indent if the line stays empty\n }\n}",
"/*\n * Fix indent for 'lisp' and 'cindent'.\n */\n void\nfix_indent(void)\n{\n if (p_paste)\n\treturn;\n if (curbuf->b_p_lisp && curbuf->b_p_ai)\n\tfixthisline(get_lisp_indent);\n else\n\tif (cindent_on())\n\t do_c_expr_indent();\n}",
"#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * \"indent()\" function\n */\n void\nf_indent(typval_T *argvars, typval_T *rettv)\n{\n linenr_T\tlnum;",
" if (in_vim9script() && check_for_lnum_arg(argvars, 0) == FAIL)\n\treturn;",
" lnum = tv_get_lnum(argvars);\n if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)\n\trettv->vval.v_number = get_indent_lnum(lnum);\n else\n {\n\tif (in_vim9script())\n\t semsg(_(e_invalid_line_number_nr), lnum);\n\trettv->vval.v_number = -1;\n }\n}",
"/*\n * \"lispindent(lnum)\" function\n */\n void\nf_lispindent(typval_T *argvars UNUSED, typval_T *rettv)\n{\n pos_T\tpos;\n linenr_T\tlnum;",
" if (in_vim9script() && check_for_lnum_arg(argvars, 0) == FAIL)\n\treturn;",
" pos = curwin->w_cursor;\n lnum = tv_get_lnum(argvars);\n if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)\n {\n\tcurwin->w_cursor.lnum = lnum;\n\trettv->vval.v_number = get_lisp_indent();\n\tcurwin->w_cursor = pos;\n }\n else if (in_vim9script())\n\tsemsg(_(e_invalid_line_number_nr), lnum);\n else\n\trettv->vval.v_number = -1;\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [2081, 87, 736], "buggy_code_start_loc": [2079, 1, 736], "filenames": ["src/indent.c", "src/testdir/test_lispwords.vim", "src/version.c"], "fixing_code_end_loc": [2084, 98, 739], "fixing_code_start_loc": [2079, 1, 737], "message": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "C88D3533-C1C8-4615-A2D5-30AC85BA943B", "versionEndExcluding": "8.2.5151", "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}, {"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": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Una Lectura Fuera de L\u00edmites en el repositorio de GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2183", "lastModified": "2023-05-03T12:15:46.177", "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-06-23T19:15:08.577", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d74ca3f9-380d-4c0a-b61c-11113cc98975"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GFD2A4YLBR7OIRHTL7CK6YNMEIQ264CN/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U743FMJGFQ35GBPCQ6OWMVZEJPDFVEWM/"}, {"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-125"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, "type": "CWE-125"}
| 319
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"\" Tests for 'lispwords' settings being global-local",
"\nset nocompatible viminfo+=nviminfo",
"func Test_global_local_lispwords()\n setglobal lispwords=foo,bar,baz\n setlocal lispwords-=foo | setlocal lispwords+=quux\n call assert_equal('foo,bar,baz', &g:lispwords)\n call assert_equal('bar,baz,quux', &l:lispwords)\n call assert_equal('bar,baz,quux', &lispwords)",
" setlocal lispwords<\n call assert_equal('foo,bar,baz', &g:lispwords)\n call assert_equal('foo,bar,baz', &l:lispwords)\n call assert_equal('foo,bar,baz', &lispwords)\nendfunc",
"func Test_lisp_indent()\n enew!",
" call append(0, [\n\t \\ '(defun html-file (base)',\n\t \\ '(format nil \"~(~A~).html\" base))',\n\t \\ '',\n\t \\ '(defmacro page (name title &rest body)',\n\t \\ '(let ((ti (gensym)))',\n\t \\ '`(with-open-file (*standard-output*',\n\t \\ '(html-file ,name)',\n\t \\ ':direction :output',\n\t \\ ':if-exists :supersede)',\n\t \\ '(let ((,ti ,title))',\n\t \\ '(as title ,ti)',\n\t \\ '(with center ',\n\t \\ '(as h2 (string-upcase ,ti)))',\n\t \\ '(brs 3)',\n\t \\ ',@body))))',\n\t \\ '',\n\t \\ ';;; Utilities for generating links',\n\t \\ '',\n\t \\ '(defmacro with-link (dest &rest body)',\n\t \\ '`(progn',\n\t \\ '(format t \"<a href=\\\"~A\\\">\" (html-file ,dest))',\n\t \\ ',@body',\n\t \\ '(princ \"</a>\")))'\n\t \\ ])\n call assert_equal(7, lispindent(2))\n call assert_equal(5, 6->lispindent())\n call assert_equal(-1, lispindent(-1))",
" set lisp\n set lispwords&\n let save_copt = &cpoptions\n set cpoptions+=p\n normal 1G=G",
" call assert_equal([\n\t \\ '(defun html-file (base)',\n\t \\ ' (format nil \"~(~A~).html\" base))',\n\t \\ '',\n\t \\ '(defmacro page (name title &rest body)',\n\t \\ ' (let ((ti (gensym)))',\n\t \\ ' `(with-open-file (*standard-output*',\n\t \\ '\t\t\t (html-file ,name)',\n\t \\ '\t\t\t :direction :output',\n\t \\ '\t\t\t :if-exists :supersede)',\n\t \\ '\t\t\t(let ((,ti ,title))',\n\t \\ '\t\t\t (as title ,ti)',\n\t \\ '\t\t\t (with center ',\n\t \\ '\t\t\t\t (as h2 (string-upcase ,ti)))',\n\t \\ '\t\t\t (brs 3)',\n\t \\ '\t\t\t ,@body))))',\n\t \\ '',\n\t \\ ';;; Utilities for generating links',\n\t \\ '',\n\t \\ '(defmacro with-link (dest &rest body)',\n\t \\ ' `(progn',\n\t \\ ' (format t \"<a href=\\\"~A\\\">\" (html-file ,dest))',\n\t \\ ' ,@body',\n\t \\ ' (princ \"</a>\")))',\n\t \\ ''\n\t \\ ], getline(1, \"$\"))",
" enew!\n let &cpoptions=save_copt\n set nolisp\nendfunc\n",
"",
"\" vim: shiftwidth=2 sts=2 expandtab"
] |
[
0,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [2081, 87, 736], "buggy_code_start_loc": [2079, 1, 736], "filenames": ["src/indent.c", "src/testdir/test_lispwords.vim", "src/version.c"], "fixing_code_end_loc": [2084, 98, 739], "fixing_code_start_loc": [2079, 1, 737], "message": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "C88D3533-C1C8-4615-A2D5-30AC85BA943B", "versionEndExcluding": "8.2.5151", "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}, {"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": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Una Lectura Fuera de L\u00edmites en el repositorio de GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2183", "lastModified": "2023-05-03T12:15:46.177", "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-06-23T19:15:08.577", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d74ca3f9-380d-4c0a-b61c-11113cc98975"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GFD2A4YLBR7OIRHTL7CK6YNMEIQ264CN/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U743FMJGFQ35GBPCQ6OWMVZEJPDFVEWM/"}, {"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-125"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, "type": "CWE-125"}
| 319
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"\" Tests for 'lispwords' settings being global-local.\n\" And other lisp indent stuff.",
"\nset nocompatible viminfo+=nviminfo",
"func Test_global_local_lispwords()\n setglobal lispwords=foo,bar,baz\n setlocal lispwords-=foo | setlocal lispwords+=quux\n call assert_equal('foo,bar,baz', &g:lispwords)\n call assert_equal('bar,baz,quux', &l:lispwords)\n call assert_equal('bar,baz,quux', &lispwords)",
" setlocal lispwords<\n call assert_equal('foo,bar,baz', &g:lispwords)\n call assert_equal('foo,bar,baz', &l:lispwords)\n call assert_equal('foo,bar,baz', &lispwords)\nendfunc",
"func Test_lisp_indent()\n enew!",
" call append(0, [\n\t \\ '(defun html-file (base)',\n\t \\ '(format nil \"~(~A~).html\" base))',\n\t \\ '',\n\t \\ '(defmacro page (name title &rest body)',\n\t \\ '(let ((ti (gensym)))',\n\t \\ '`(with-open-file (*standard-output*',\n\t \\ '(html-file ,name)',\n\t \\ ':direction :output',\n\t \\ ':if-exists :supersede)',\n\t \\ '(let ((,ti ,title))',\n\t \\ '(as title ,ti)',\n\t \\ '(with center ',\n\t \\ '(as h2 (string-upcase ,ti)))',\n\t \\ '(brs 3)',\n\t \\ ',@body))))',\n\t \\ '',\n\t \\ ';;; Utilities for generating links',\n\t \\ '',\n\t \\ '(defmacro with-link (dest &rest body)',\n\t \\ '`(progn',\n\t \\ '(format t \"<a href=\\\"~A\\\">\" (html-file ,dest))',\n\t \\ ',@body',\n\t \\ '(princ \"</a>\")))'\n\t \\ ])\n call assert_equal(7, lispindent(2))\n call assert_equal(5, 6->lispindent())\n call assert_equal(-1, lispindent(-1))",
" set lisp\n set lispwords&\n let save_copt = &cpoptions\n set cpoptions+=p\n normal 1G=G",
" call assert_equal([\n\t \\ '(defun html-file (base)',\n\t \\ ' (format nil \"~(~A~).html\" base))',\n\t \\ '',\n\t \\ '(defmacro page (name title &rest body)',\n\t \\ ' (let ((ti (gensym)))',\n\t \\ ' `(with-open-file (*standard-output*',\n\t \\ '\t\t\t (html-file ,name)',\n\t \\ '\t\t\t :direction :output',\n\t \\ '\t\t\t :if-exists :supersede)',\n\t \\ '\t\t\t(let ((,ti ,title))',\n\t \\ '\t\t\t (as title ,ti)',\n\t \\ '\t\t\t (with center ',\n\t \\ '\t\t\t\t (as h2 (string-upcase ,ti)))',\n\t \\ '\t\t\t (brs 3)',\n\t \\ '\t\t\t ,@body))))',\n\t \\ '',\n\t \\ ';;; Utilities for generating links',\n\t \\ '',\n\t \\ '(defmacro with-link (dest &rest body)',\n\t \\ ' `(progn',\n\t \\ ' (format t \"<a href=\\\"~A\\\">\" (html-file ,dest))',\n\t \\ ' ,@body',\n\t \\ ' (princ \"</a>\")))',\n\t \\ ''\n\t \\ ], getline(1, \"$\"))",
" enew!\n let &cpoptions=save_copt\n set nolisp\nendfunc\n",
"func Test_lisp_indent_works()\n \" This was reading beyond the end of the line\n new\n exe \"norm a\\tü(\\<CR>=\"\n set lisp\n norm ==\n bwipe!\nendfunc\n",
"\" vim: shiftwidth=2 sts=2 expandtab"
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
PreciseBugs
|
{"buggy_code_end_loc": [2081, 87, 736], "buggy_code_start_loc": [2079, 1, 736], "filenames": ["src/indent.c", "src/testdir/test_lispwords.vim", "src/version.c"], "fixing_code_end_loc": [2084, 98, 739], "fixing_code_start_loc": [2079, 1, 737], "message": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "C88D3533-C1C8-4615-A2D5-30AC85BA943B", "versionEndExcluding": "8.2.5151", "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}, {"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": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Una Lectura Fuera de L\u00edmites en el repositorio de GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2183", "lastModified": "2023-05-03T12:15:46.177", "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-06-23T19:15:08.577", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d74ca3f9-380d-4c0a-b61c-11113cc98975"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GFD2A4YLBR7OIRHTL7CK6YNMEIQ264CN/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U743FMJGFQ35GBPCQ6OWMVZEJPDFVEWM/"}, {"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-125"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, "type": "CWE-125"}
| 319
|
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 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 5150,\n/**/\n 5149,\n/**/\n 5148,\n/**/\n 5147,\n/**/\n 5146,\n/**/\n 5145,\n/**/\n 5144,\n/**/\n 5143,\n/**/\n 5142,\n/**/\n 5141,\n/**/\n 5140,\n/**/\n 5139,\n/**/\n 5138,\n/**/\n 5137,\n/**/\n 5136,\n/**/\n 5135,\n/**/\n 5134,\n/**/\n 5133,\n/**/\n 5132,\n/**/\n 5131,\n/**/\n 5130,\n/**/\n 5129,\n/**/\n 5128,\n/**/\n 5127,\n/**/\n 5126,\n/**/\n 5125,\n/**/\n 5124,\n/**/\n 5123,\n/**/\n 5122,\n/**/\n 5121,\n/**/\n 5120,\n/**/\n 5119,\n/**/\n 5118,\n/**/\n 5117,\n/**/\n 5116,\n/**/\n 5115,\n/**/\n 5114,\n/**/\n 5113,\n/**/\n 5112,\n/**/\n 5111,\n/**/\n 5110,\n/**/\n 5109,\n/**/\n 5108,\n/**/\n 5107,\n/**/\n 5106,\n/**/\n 5105,\n/**/\n 5104,\n/**/\n 5103,\n/**/\n 5102,\n/**/\n 5101,\n/**/\n 5100,\n/**/\n 5099,\n/**/\n 5098,\n/**/\n 5097,\n/**/\n 5096,\n/**/\n 5095,\n/**/\n 5094,\n/**/\n 5093,\n/**/\n 5092,\n/**/\n 5091,\n/**/\n 5090,\n/**/\n 5089,\n/**/\n 5088,\n/**/\n 5087,\n/**/\n 5086,\n/**/\n 5085,\n/**/\n 5084,\n/**/\n 5083,\n/**/\n 5082,\n/**/\n 5081,\n/**/\n 5080,\n/**/\n 5079,\n/**/\n 5078,\n/**/\n 5077,\n/**/\n 5076,\n/**/\n 5075,\n/**/\n 5074,\n/**/\n 5073,\n/**/\n 5072,\n/**/\n 5071,\n/**/\n 5070,\n/**/\n 5069,\n/**/\n 5068,\n/**/\n 5067,\n/**/\n 5066,\n/**/\n 5065,\n/**/\n 5064,\n/**/\n 5063,\n/**/\n 5062,\n/**/\n 5061,\n/**/\n 5060,\n/**/\n 5059,\n/**/\n 5058,\n/**/\n 5057,\n/**/\n 5056,\n/**/\n 5055,\n/**/\n 5054,\n/**/\n 5053,\n/**/\n 5052,\n/**/\n 5051,\n/**/\n 5050,\n/**/\n 5049,\n/**/\n 5048,\n/**/\n 5047,\n/**/\n 5046,\n/**/\n 5045,\n/**/\n 5044,\n/**/\n 5043,\n/**/\n 5042,\n/**/\n 5041,\n/**/\n 5040,\n/**/\n 5039,\n/**/\n 5038,\n/**/\n 5037,\n/**/\n 5036,\n/**/\n 5035,\n/**/\n 5034,\n/**/\n 5033,\n/**/\n 5032,\n/**/\n 5031,\n/**/\n 5030,\n/**/\n 5029,\n/**/\n 5028,\n/**/\n 5027,\n/**/\n 5026,\n/**/\n 5025,\n/**/\n 5024,\n/**/\n 5023,\n/**/\n 5022,\n/**/\n 5021,\n/**/\n 5020,\n/**/\n 5019,\n/**/\n 5018,\n/**/\n 5017,\n/**/\n 5016,\n/**/\n 5015,\n/**/\n 5014,\n/**/\n 5013,\n/**/\n 5012,\n/**/\n 5011,\n/**/\n 5010,\n/**/\n 5009,\n/**/\n 5008,\n/**/\n 5007,\n/**/\n 5006,\n/**/\n 5005,\n/**/\n 5004,\n/**/\n 5003,\n/**/\n 5002,\n/**/\n 5001,\n/**/\n 5000,\n/**/\n 4999,\n/**/\n 4998,\n/**/\n 4997,\n/**/\n 4996,\n/**/\n 4995,\n/**/\n 4994,\n/**/\n 4993,\n/**/\n 4992,\n/**/\n 4991,\n/**/\n 4990,\n/**/\n 4989,\n/**/\n 4988,\n/**/\n 4987,\n/**/\n 4986,\n/**/\n 4985,\n/**/\n 4984,\n/**/\n 4983,\n/**/\n 4982,\n/**/\n 4981,\n/**/\n 4980,\n/**/\n 4979,\n/**/\n 4978,\n/**/\n 4977,\n/**/\n 4976,\n/**/\n 4975,\n/**/\n 4974,\n/**/\n 4973,\n/**/\n 4972,\n/**/\n 4971,\n/**/\n 4970,\n/**/\n 4969,\n/**/\n 4968,\n/**/\n 4967,\n/**/\n 4966,\n/**/\n 4965,\n/**/\n 4964,\n/**/\n 4963,\n/**/\n 4962,\n/**/\n 4961,\n/**/\n 4960,\n/**/\n 4959,\n/**/\n 4958,\n/**/\n 4957,\n/**/\n 4956,\n/**/\n 4955,\n/**/\n 4954,\n/**/\n 4953,\n/**/\n 4952,\n/**/\n 4951,\n/**/\n 4950,\n/**/\n 4949,\n/**/\n 4948,\n/**/\n 4947,\n/**/\n 4946,\n/**/\n 4945,\n/**/\n 4944,\n/**/\n 4943,\n/**/\n 4942,\n/**/\n 4941,\n/**/\n 4940,\n/**/\n 4939,\n/**/\n 4938,\n/**/\n 4937,\n/**/\n 4936,\n/**/\n 4935,\n/**/\n 4934,\n/**/\n 4933,\n/**/\n 4932,\n/**/\n 4931,\n/**/\n 4930,\n/**/\n 4929,\n/**/\n 4928,\n/**/\n 4927,\n/**/\n 4926,\n/**/\n 4925,\n/**/\n 4924,\n/**/\n 4923,\n/**/\n 4922,\n/**/\n 4921,\n/**/\n 4920,\n/**/\n 4919,\n/**/\n 4918,\n/**/\n 4917,\n/**/\n 4916,\n/**/\n 4915,\n/**/\n 4914,\n/**/\n 4913,\n/**/\n 4912,\n/**/\n 4911,\n/**/\n 4910,\n/**/\n 4909,\n/**/\n 4908,\n/**/\n 4907,\n/**/\n 4906,\n/**/\n 4905,\n/**/\n 4904,\n/**/\n 4903,\n/**/\n 4902,\n/**/\n 4901,\n/**/\n 4900,\n/**/\n 4899,\n/**/\n 4898,\n/**/\n 4897,\n/**/\n 4896,\n/**/\n 4895,\n/**/\n 4894,\n/**/\n 4893,\n/**/\n 4892,\n/**/\n 4891,\n/**/\n 4890,\n/**/\n 4889,\n/**/\n 4888,\n/**/\n 4887,\n/**/\n 4886,\n/**/\n 4885,\n/**/\n 4884,\n/**/\n 4883,\n/**/\n 4882,\n/**/\n 4881,\n/**/\n 4880,\n/**/\n 4879,\n/**/\n 4878,\n/**/\n 4877,\n/**/\n 4876,\n/**/\n 4875,\n/**/\n 4874,\n/**/\n 4873,\n/**/\n 4872,\n/**/\n 4871,\n/**/\n 4870,\n/**/\n 4869,\n/**/\n 4868,\n/**/\n 4867,\n/**/\n 4866,\n/**/\n 4865,\n/**/\n 4864,\n/**/\n 4863,\n/**/\n 4862,\n/**/\n 4861,\n/**/\n 4860,\n/**/\n 4859,\n/**/\n 4858,\n/**/\n 4857,\n/**/\n 4856,\n/**/\n 4855,\n/**/\n 4854,\n/**/\n 4853,\n/**/\n 4852,\n/**/\n 4851,\n/**/\n 4850,\n/**/\n 4849,\n/**/\n 4848,\n/**/\n 4847,\n/**/\n 4846,\n/**/\n 4845,\n/**/\n 4844,\n/**/\n 4843,\n/**/\n 4842,\n/**/\n 4841,\n/**/\n 4840,\n/**/\n 4839,\n/**/\n 4838,\n/**/\n 4837,\n/**/\n 4836,\n/**/\n 4835,\n/**/\n 4834,\n/**/\n 4833,\n/**/\n 4832,\n/**/\n 4831,\n/**/\n 4830,\n/**/\n 4829,\n/**/\n 4828,\n/**/\n 4827,\n/**/\n 4826,\n/**/\n 4825,\n/**/\n 4824,\n/**/\n 4823,\n/**/\n 4822,\n/**/\n 4821,\n/**/\n 4820,\n/**/\n 4819,\n/**/\n 4818,\n/**/\n 4817,\n/**/\n 4816,\n/**/\n 4815,\n/**/\n 4814,\n/**/\n 4813,\n/**/\n 4812,\n/**/\n 4811,\n/**/\n 4810,\n/**/\n 4809,\n/**/\n 4808,\n/**/\n 4807,\n/**/\n 4806,\n/**/\n 4805,\n/**/\n 4804,\n/**/\n 4803,\n/**/\n 4802,\n/**/\n 4801,\n/**/\n 4800,\n/**/\n 4799,\n/**/\n 4798,\n/**/\n 4797,\n/**/\n 4796,\n/**/\n 4795,\n/**/\n 4794,\n/**/\n 4793,\n/**/\n 4792,\n/**/\n 4791,\n/**/\n 4790,\n/**/\n 4789,\n/**/\n 4788,\n/**/\n 4787,\n/**/\n 4786,\n/**/\n 4785,\n/**/\n 4784,\n/**/\n 4783,\n/**/\n 4782,\n/**/\n 4781,\n/**/\n 4780,\n/**/\n 4779,\n/**/\n 4778,\n/**/\n 4777,\n/**/\n 4776,\n/**/\n 4775,\n/**/\n 4774,\n/**/\n 4773,\n/**/\n 4772,\n/**/\n 4771,\n/**/\n 4770,\n/**/\n 4769,\n/**/\n 4768,\n/**/\n 4767,\n/**/\n 4766,\n/**/\n 4765,\n/**/\n 4764,\n/**/\n 4763,\n/**/\n 4762,\n/**/\n 4761,\n/**/\n 4760,\n/**/\n 4759,\n/**/\n 4758,\n/**/\n 4757,\n/**/\n 4756,\n/**/\n 4755,\n/**/\n 4754,\n/**/\n 4753,\n/**/\n 4752,\n/**/\n 4751,\n/**/\n 4750,\n/**/\n 4749,\n/**/\n 4748,\n/**/\n 4747,\n/**/\n 4746,\n/**/\n 4745,\n/**/\n 4744,\n/**/\n 4743,\n/**/\n 4742,\n/**/\n 4741,\n/**/\n 4740,\n/**/\n 4739,\n/**/\n 4738,\n/**/\n 4737,\n/**/\n 4736,\n/**/\n 4735,\n/**/\n 4734,\n/**/\n 4733,\n/**/\n 4732,\n/**/\n 4731,\n/**/\n 4730,\n/**/\n 4729,\n/**/\n 4728,\n/**/\n 4727,\n/**/\n 4726,\n/**/\n 4725,\n/**/\n 4724,\n/**/\n 4723,\n/**/\n 4722,\n/**/\n 4721,\n/**/\n 4720,\n/**/\n 4719,\n/**/\n 4718,\n/**/\n 4717,\n/**/\n 4716,\n/**/\n 4715,\n/**/\n 4714,\n/**/\n 4713,\n/**/\n 4712,\n/**/\n 4711,\n/**/\n 4710,\n/**/\n 4709,\n/**/\n 4708,\n/**/\n 4707,\n/**/\n 4706,\n/**/\n 4705,\n/**/\n 4704,\n/**/\n 4703,\n/**/\n 4702,\n/**/\n 4701,\n/**/\n 4700,\n/**/\n 4699,\n/**/\n 4698,\n/**/\n 4697,\n/**/\n 4696,\n/**/\n 4695,\n/**/\n 4694,\n/**/\n 4693,\n/**/\n 4692,\n/**/\n 4691,\n/**/\n 4690,\n/**/\n 4689,\n/**/\n 4688,\n/**/\n 4687,\n/**/\n 4686,\n/**/\n 4685,\n/**/\n 4684,\n/**/\n 4683,\n/**/\n 4682,\n/**/\n 4681,\n/**/\n 4680,\n/**/\n 4679,\n/**/\n 4678,\n/**/\n 4677,\n/**/\n 4676,\n/**/\n 4675,\n/**/\n 4674,\n/**/\n 4673,\n/**/\n 4672,\n/**/\n 4671,\n/**/\n 4670,\n/**/\n 4669,\n/**/\n 4668,\n/**/\n 4667,\n/**/\n 4666,\n/**/\n 4665,\n/**/\n 4664,\n/**/\n 4663,\n/**/\n 4662,\n/**/\n 4661,\n/**/\n 4660,\n/**/\n 4659,\n/**/\n 4658,\n/**/\n 4657,\n/**/\n 4656,\n/**/\n 4655,\n/**/\n 4654,\n/**/\n 4653,\n/**/\n 4652,\n/**/\n 4651,\n/**/\n 4650,\n/**/\n 4649,\n/**/\n 4648,\n/**/\n 4647,\n/**/\n 4646,\n/**/\n 4645,\n/**/\n 4644,\n/**/\n 4643,\n/**/\n 4642,\n/**/\n 4641,\n/**/\n 4640,\n/**/\n 4639,\n/**/\n 4638,\n/**/\n 4637,\n/**/\n 4636,\n/**/\n 4635,\n/**/\n 4634,\n/**/\n 4633,\n/**/\n 4632,\n/**/\n 4631,\n/**/\n 4630,\n/**/\n 4629,\n/**/\n 4628,\n/**/\n 4627,\n/**/\n 4626,\n/**/\n 4625,\n/**/\n 4624,\n/**/\n 4623,\n/**/\n 4622,\n/**/\n 4621,\n/**/\n 4620,\n/**/\n 4619,\n/**/\n 4618,\n/**/\n 4617,\n/**/\n 4616,\n/**/\n 4615,\n/**/\n 4614,\n/**/\n 4613,\n/**/\n 4612,\n/**/\n 4611,\n/**/\n 4610,\n/**/\n 4609,\n/**/\n 4608,\n/**/\n 4607,\n/**/\n 4606,\n/**/\n 4605,\n/**/\n 4604,\n/**/\n 4603,\n/**/\n 4602,\n/**/\n 4601,\n/**/\n 4600,\n/**/\n 4599,\n/**/\n 4598,\n/**/\n 4597,\n/**/\n 4596,\n/**/\n 4595,\n/**/\n 4594,\n/**/\n 4593,\n/**/\n 4592,\n/**/\n 4591,\n/**/\n 4590,\n/**/\n 4589,\n/**/\n 4588,\n/**/\n 4587,\n/**/\n 4586,\n/**/\n 4585,\n/**/\n 4584,\n/**/\n 4583,\n/**/\n 4582,\n/**/\n 4581,\n/**/\n 4580,\n/**/\n 4579,\n/**/\n 4578,\n/**/\n 4577,\n/**/\n 4576,\n/**/\n 4575,\n/**/\n 4574,\n/**/\n 4573,\n/**/\n 4572,\n/**/\n 4571,\n/**/\n 4570,\n/**/\n 4569,\n/**/\n 4568,\n/**/\n 4567,\n/**/\n 4566,\n/**/\n 4565,\n/**/\n 4564,\n/**/\n 4563,\n/**/\n 4562,\n/**/\n 4561,\n/**/\n 4560,\n/**/\n 4559,\n/**/\n 4558,\n/**/\n 4557,\n/**/\n 4556,\n/**/\n 4555,\n/**/\n 4554,\n/**/\n 4553,\n/**/\n 4552,\n/**/\n 4551,\n/**/\n 4550,\n/**/\n 4549,\n/**/\n 4548,\n/**/\n 4547,\n/**/\n 4546,\n/**/\n 4545,\n/**/\n 4544,\n/**/\n 4543,\n/**/\n 4542,\n/**/\n 4541,\n/**/\n 4540,\n/**/\n 4539,\n/**/\n 4538,\n/**/\n 4537,\n/**/\n 4536,\n/**/\n 4535,\n/**/\n 4534,\n/**/\n 4533,\n/**/\n 4532,\n/**/\n 4531,\n/**/\n 4530,\n/**/\n 4529,\n/**/\n 4528,\n/**/\n 4527,\n/**/\n 4526,\n/**/\n 4525,\n/**/\n 4524,\n/**/\n 4523,\n/**/\n 4522,\n/**/\n 4521,\n/**/\n 4520,\n/**/\n 4519,\n/**/\n 4518,\n/**/\n 4517,\n/**/\n 4516,\n/**/\n 4515,\n/**/\n 4514,\n/**/\n 4513,\n/**/\n 4512,\n/**/\n 4511,\n/**/\n 4510,\n/**/\n 4509,\n/**/\n 4508,\n/**/\n 4507,\n/**/\n 4506,\n/**/\n 4505,\n/**/\n 4504,\n/**/\n 4503,\n/**/\n 4502,\n/**/\n 4501,\n/**/\n 4500,\n/**/\n 4499,\n/**/\n 4498,\n/**/\n 4497,\n/**/\n 4496,\n/**/\n 4495,\n/**/\n 4494,\n/**/\n 4493,\n/**/\n 4492,\n/**/\n 4491,\n/**/\n 4490,\n/**/\n 4489,\n/**/\n 4488,\n/**/\n 4487,\n/**/\n 4486,\n/**/\n 4485,\n/**/\n 4484,\n/**/\n 4483,\n/**/\n 4482,\n/**/\n 4481,\n/**/\n 4480,\n/**/\n 4479,\n/**/\n 4478,\n/**/\n 4477,\n/**/\n 4476,\n/**/\n 4475,\n/**/\n 4474,\n/**/\n 4473,\n/**/\n 4472,\n/**/\n 4471,\n/**/\n 4470,\n/**/\n 4469,\n/**/\n 4468,\n/**/\n 4467,\n/**/\n 4466,\n/**/\n 4465,\n/**/\n 4464,\n/**/\n 4463,\n/**/\n 4462,\n/**/\n 4461,\n/**/\n 4460,\n/**/\n 4459,\n/**/\n 4458,\n/**/\n 4457,\n/**/\n 4456,\n/**/\n 4455,\n/**/\n 4454,\n/**/\n 4453,\n/**/\n 4452,\n/**/\n 4451,\n/**/\n 4450,\n/**/\n 4449,\n/**/\n 4448,\n/**/\n 4447,\n/**/\n 4446,\n/**/\n 4445,\n/**/\n 4444,\n/**/\n 4443,\n/**/\n 4442,\n/**/\n 4441,\n/**/\n 4440,\n/**/\n 4439,\n/**/\n 4438,\n/**/\n 4437,\n/**/\n 4436,\n/**/\n 4435,\n/**/\n 4434,\n/**/\n 4433,\n/**/\n 4432,\n/**/\n 4431,\n/**/\n 4430,\n/**/\n 4429,\n/**/\n 4428,\n/**/\n 4427,\n/**/\n 4426,\n/**/\n 4425,\n/**/\n 4424,\n/**/\n 4423,\n/**/\n 4422,\n/**/\n 4421,\n/**/\n 4420,\n/**/\n 4419,\n/**/\n 4418,\n/**/\n 4417,\n/**/\n 4416,\n/**/\n 4415,\n/**/\n 4414,\n/**/\n 4413,\n/**/\n 4412,\n/**/\n 4411,\n/**/\n 4410,\n/**/\n 4409,\n/**/\n 4408,\n/**/\n 4407,\n/**/\n 4406,\n/**/\n 4405,\n/**/\n 4404,\n/**/\n 4403,\n/**/\n 4402,\n/**/\n 4401,\n/**/\n 4400,\n/**/\n 4399,\n/**/\n 4398,\n/**/\n 4397,\n/**/\n 4396,\n/**/\n 4395,\n/**/\n 4394,\n/**/\n 4393,\n/**/\n 4392,\n/**/\n 4391,\n/**/\n 4390,\n/**/\n 4389,\n/**/\n 4388,\n/**/\n 4387,\n/**/\n 4386,\n/**/\n 4385,\n/**/\n 4384,\n/**/\n 4383,\n/**/\n 4382,\n/**/\n 4381,\n/**/\n 4380,\n/**/\n 4379,\n/**/\n 4378,\n/**/\n 4377,\n/**/\n 4376,\n/**/\n 4375,\n/**/\n 4374,\n/**/\n 4373,\n/**/\n 4372,\n/**/\n 4371,\n/**/\n 4370,\n/**/\n 4369,\n/**/\n 4368,\n/**/\n 4367,\n/**/\n 4366,\n/**/\n 4365,\n/**/\n 4364,\n/**/\n 4363,\n/**/\n 4362,\n/**/\n 4361,\n/**/\n 4360,\n/**/\n 4359,\n/**/\n 4358,\n/**/\n 4357,\n/**/\n 4356,\n/**/\n 4355,\n/**/\n 4354,\n/**/\n 4353,\n/**/\n 4352,\n/**/\n 4351,\n/**/\n 4350,\n/**/\n 4349,\n/**/\n 4348,\n/**/\n 4347,\n/**/\n 4346,\n/**/\n 4345,\n/**/\n 4344,\n/**/\n 4343,\n/**/\n 4342,\n/**/\n 4341,\n/**/\n 4340,\n/**/\n 4339,\n/**/\n 4338,\n/**/\n 4337,\n/**/\n 4336,\n/**/\n 4335,\n/**/\n 4334,\n/**/\n 4333,\n/**/\n 4332,\n/**/\n 4331,\n/**/\n 4330,\n/**/\n 4329,\n/**/\n 4328,\n/**/\n 4327,\n/**/\n 4326,\n/**/\n 4325,\n/**/\n 4324,\n/**/\n 4323,\n/**/\n 4322,\n/**/\n 4321,\n/**/\n 4320,\n/**/\n 4319,\n/**/\n 4318,\n/**/\n 4317,\n/**/\n 4316,\n/**/\n 4315,\n/**/\n 4314,\n/**/\n 4313,\n/**/\n 4312,\n/**/\n 4311,\n/**/\n 4310,\n/**/\n 4309,\n/**/\n 4308,\n/**/\n 4307,\n/**/\n 4306,\n/**/\n 4305,\n/**/\n 4304,\n/**/\n 4303,\n/**/\n 4302,\n/**/\n 4301,\n/**/\n 4300,\n/**/\n 4299,\n/**/\n 4298,\n/**/\n 4297,\n/**/\n 4296,\n/**/\n 4295,\n/**/\n 4294,\n/**/\n 4293,\n/**/\n 4292,\n/**/\n 4291,\n/**/\n 4290,\n/**/\n 4289,\n/**/\n 4288,\n/**/\n 4287,\n/**/\n 4286,\n/**/\n 4285,\n/**/\n 4284,\n/**/\n 4283,\n/**/\n 4282,\n/**/\n 4281,\n/**/\n 4280,\n/**/\n 4279,\n/**/\n 4278,\n/**/\n 4277,\n/**/\n 4276,\n/**/\n 4275,\n/**/\n 4274,\n/**/\n 4273,\n/**/\n 4272,\n/**/\n 4271,\n/**/\n 4270,\n/**/\n 4269,\n/**/\n 4268,\n/**/\n 4267,\n/**/\n 4266,\n/**/\n 4265,\n/**/\n 4264,\n/**/\n 4263,\n/**/\n 4262,\n/**/\n 4261,\n/**/\n 4260,\n/**/\n 4259,\n/**/\n 4258,\n/**/\n 4257,\n/**/\n 4256,\n/**/\n 4255,\n/**/\n 4254,\n/**/\n 4253,\n/**/\n 4252,\n/**/\n 4251,\n/**/\n 4250,\n/**/\n 4249,\n/**/\n 4248,\n/**/\n 4247,\n/**/\n 4246,\n/**/\n 4245,\n/**/\n 4244,\n/**/\n 4243,\n/**/\n 4242,\n/**/\n 4241,\n/**/\n 4240,\n/**/\n 4239,\n/**/\n 4238,\n/**/\n 4237,\n/**/\n 4236,\n/**/\n 4235,\n/**/\n 4234,\n/**/\n 4233,\n/**/\n 4232,\n/**/\n 4231,\n/**/\n 4230,\n/**/\n 4229,\n/**/\n 4228,\n/**/\n 4227,\n/**/\n 4226,\n/**/\n 4225,\n/**/\n 4224,\n/**/\n 4223,\n/**/\n 4222,\n/**/\n 4221,\n/**/\n 4220,\n/**/\n 4219,\n/**/\n 4218,\n/**/\n 4217,\n/**/\n 4216,\n/**/\n 4215,\n/**/\n 4214,\n/**/\n 4213,\n/**/\n 4212,\n/**/\n 4211,\n/**/\n 4210,\n/**/\n 4209,\n/**/\n 4208,\n/**/\n 4207,\n/**/\n 4206,\n/**/\n 4205,\n/**/\n 4204,\n/**/\n 4203,\n/**/\n 4202,\n/**/\n 4201,\n/**/\n 4200,\n/**/\n 4199,\n/**/\n 4198,\n/**/\n 4197,\n/**/\n 4196,\n/**/\n 4195,\n/**/\n 4194,\n/**/\n 4193,\n/**/\n 4192,\n/**/\n 4191,\n/**/\n 4190,\n/**/\n 4189,\n/**/\n 4188,\n/**/\n 4187,\n/**/\n 4186,\n/**/\n 4185,\n/**/\n 4184,\n/**/\n 4183,\n/**/\n 4182,\n/**/\n 4181,\n/**/\n 4180,\n/**/\n 4179,\n/**/\n 4178,\n/**/\n 4177,\n/**/\n 4176,\n/**/\n 4175,\n/**/\n 4174,\n/**/\n 4173,\n/**/\n 4172,\n/**/\n 4171,\n/**/\n 4170,\n/**/\n 4169,\n/**/\n 4168,\n/**/\n 4167,\n/**/\n 4166,\n/**/\n 4165,\n/**/\n 4164,\n/**/\n 4163,\n/**/\n 4162,\n/**/\n 4161,\n/**/\n 4160,\n/**/\n 4159,\n/**/\n 4158,\n/**/\n 4157,\n/**/\n 4156,\n/**/\n 4155,\n/**/\n 4154,\n/**/\n 4153,\n/**/\n 4152,\n/**/\n 4151,\n/**/\n 4150,\n/**/\n 4149,\n/**/\n 4148,\n/**/\n 4147,\n/**/\n 4146,\n/**/\n 4145,\n/**/\n 4144,\n/**/\n 4143,\n/**/\n 4142,\n/**/\n 4141,\n/**/\n 4140,\n/**/\n 4139,\n/**/\n 4138,\n/**/\n 4137,\n/**/\n 4136,\n/**/\n 4135,\n/**/\n 4134,\n/**/\n 4133,\n/**/\n 4132,\n/**/\n 4131,\n/**/\n 4130,\n/**/\n 4129,\n/**/\n 4128,\n/**/\n 4127,\n/**/\n 4126,\n/**/\n 4125,\n/**/\n 4124,\n/**/\n 4123,\n/**/\n 4122,\n/**/\n 4121,\n/**/\n 4120,\n/**/\n 4119,\n/**/\n 4118,\n/**/\n 4117,\n/**/\n 4116,\n/**/\n 4115,\n/**/\n 4114,\n/**/\n 4113,\n/**/\n 4112,\n/**/\n 4111,\n/**/\n 4110,\n/**/\n 4109,\n/**/\n 4108,\n/**/\n 4107,\n/**/\n 4106,\n/**/\n 4105,\n/**/\n 4104,\n/**/\n 4103,\n/**/\n 4102,\n/**/\n 4101,\n/**/\n 4100,\n/**/\n 4099,\n/**/\n 4098,\n/**/\n 4097,\n/**/\n 4096,\n/**/\n 4095,\n/**/\n 4094,\n/**/\n 4093,\n/**/\n 4092,\n/**/\n 4091,\n/**/\n 4090,\n/**/\n 4089,\n/**/\n 4088,\n/**/\n 4087,\n/**/\n 4086,\n/**/\n 4085,\n/**/\n 4084,\n/**/\n 4083,\n/**/\n 4082,\n/**/\n 4081,\n/**/\n 4080,\n/**/\n 4079,\n/**/\n 4078,\n/**/\n 4077,\n/**/\n 4076,\n/**/\n 4075,\n/**/\n 4074,\n/**/\n 4073,\n/**/\n 4072,\n/**/\n 4071,\n/**/\n 4070,\n/**/\n 4069,\n/**/\n 4068,\n/**/\n 4067,\n/**/\n 4066,\n/**/\n 4065,\n/**/\n 4064,\n/**/\n 4063,\n/**/\n 4062,\n/**/\n 4061,\n/**/\n 4060,\n/**/\n 4059,\n/**/\n 4058,\n/**/\n 4057,\n/**/\n 4056,\n/**/\n 4055,\n/**/\n 4054,\n/**/\n 4053,\n/**/\n 4052,\n/**/\n 4051,\n/**/\n 4050,\n/**/\n 4049,\n/**/\n 4048,\n/**/\n 4047,\n/**/\n 4046,\n/**/\n 4045,\n/**/\n 4044,\n/**/\n 4043,\n/**/\n 4042,\n/**/\n 4041,\n/**/\n 4040,\n/**/\n 4039,\n/**/\n 4038,\n/**/\n 4037,\n/**/\n 4036,\n/**/\n 4035,\n/**/\n 4034,\n/**/\n 4033,\n/**/\n 4032,\n/**/\n 4031,\n/**/\n 4030,\n/**/\n 4029,\n/**/\n 4028,\n/**/\n 4027,\n/**/\n 4026,\n/**/\n 4025,\n/**/\n 4024,\n/**/\n 4023,\n/**/\n 4022,\n/**/\n 4021,\n/**/\n 4020,\n/**/\n 4019,\n/**/\n 4018,\n/**/\n 4017,\n/**/\n 4016,\n/**/\n 4015,\n/**/\n 4014,\n/**/\n 4013,\n/**/\n 4012,\n/**/\n 4011,\n/**/\n 4010,\n/**/\n 4009,\n/**/\n 4008,\n/**/\n 4007,\n/**/\n 4006,\n/**/\n 4005,\n/**/\n 4004,\n/**/\n 4003,\n/**/\n 4002,\n/**/\n 4001,\n/**/\n 4000,\n/**/\n 3999,\n/**/\n 3998,\n/**/\n 3997,\n/**/\n 3996,\n/**/\n 3995,\n/**/\n 3994,\n/**/\n 3993,\n/**/\n 3992,\n/**/\n 3991,\n/**/\n 3990,\n/**/\n 3989,\n/**/\n 3988,\n/**/\n 3987,\n/**/\n 3986,\n/**/\n 3985,\n/**/\n 3984,\n/**/\n 3983,\n/**/\n 3982,\n/**/\n 3981,\n/**/\n 3980,\n/**/\n 3979,\n/**/\n 3978,\n/**/\n 3977,\n/**/\n 3976,\n/**/\n 3975,\n/**/\n 3974,\n/**/\n 3973,\n/**/\n 3972,\n/**/\n 3971,\n/**/\n 3970,\n/**/\n 3969,\n/**/\n 3968,\n/**/\n 3967,\n/**/\n 3966,\n/**/\n 3965,\n/**/\n 3964,\n/**/\n 3963,\n/**/\n 3962,\n/**/\n 3961,\n/**/\n 3960,\n/**/\n 3959,\n/**/\n 3958,\n/**/\n 3957,\n/**/\n 3956,\n/**/\n 3955,\n/**/\n 3954,\n/**/\n 3953,\n/**/\n 3952,\n/**/\n 3951,\n/**/\n 3950,\n/**/\n 3949,\n/**/\n 3948,\n/**/\n 3947,\n/**/\n 3946,\n/**/\n 3945,\n/**/\n 3944,\n/**/\n 3943,\n/**/\n 3942,\n/**/\n 3941,\n/**/\n 3940,\n/**/\n 3939,\n/**/\n 3938,\n/**/\n 3937,\n/**/\n 3936,\n/**/\n 3935,\n/**/\n 3934,\n/**/\n 3933,\n/**/\n 3932,\n/**/\n 3931,\n/**/\n 3930,\n/**/\n 3929,\n/**/\n 3928,\n/**/\n 3927,\n/**/\n 3926,\n/**/\n 3925,\n/**/\n 3924,\n/**/\n 3923,\n/**/\n 3922,\n/**/\n 3921,\n/**/\n 3920,\n/**/\n 3919,\n/**/\n 3918,\n/**/\n 3917,\n/**/\n 3916,\n/**/\n 3915,\n/**/\n 3914,\n/**/\n 3913,\n/**/\n 3912,\n/**/\n 3911,\n/**/\n 3910,\n/**/\n 3909,\n/**/\n 3908,\n/**/\n 3907,\n/**/\n 3906,\n/**/\n 3905,\n/**/\n 3904,\n/**/\n 3903,\n/**/\n 3902,\n/**/\n 3901,\n/**/\n 3900,\n/**/\n 3899,\n/**/\n 3898,\n/**/\n 3897,\n/**/\n 3896,\n/**/\n 3895,\n/**/\n 3894,\n/**/\n 3893,\n/**/\n 3892,\n/**/\n 3891,\n/**/\n 3890,\n/**/\n 3889,\n/**/\n 3888,\n/**/\n 3887,\n/**/\n 3886,\n/**/\n 3885,\n/**/\n 3884,\n/**/\n 3883,\n/**/\n 3882,\n/**/\n 3881,\n/**/\n 3880,\n/**/\n 3879,\n/**/\n 3878,\n/**/\n 3877,\n/**/\n 3876,\n/**/\n 3875,\n/**/\n 3874,\n/**/\n 3873,\n/**/\n 3872,\n/**/\n 3871,\n/**/\n 3870,\n/**/\n 3869,\n/**/\n 3868,\n/**/\n 3867,\n/**/\n 3866,\n/**/\n 3865,\n/**/\n 3864,\n/**/\n 3863,\n/**/\n 3862,\n/**/\n 3861,\n/**/\n 3860,\n/**/\n 3859,\n/**/\n 3858,\n/**/\n 3857,\n/**/\n 3856,\n/**/\n 3855,\n/**/\n 3854,\n/**/\n 3853,\n/**/\n 3852,\n/**/\n 3851,\n/**/\n 3850,\n/**/\n 3849,\n/**/\n 3848,\n/**/\n 3847,\n/**/\n 3846,\n/**/\n 3845,\n/**/\n 3844,\n/**/\n 3843,\n/**/\n 3842,\n/**/\n 3841,\n/**/\n 3840,\n/**/\n 3839,\n/**/\n 3838,\n/**/\n 3837,\n/**/\n 3836,\n/**/\n 3835,\n/**/\n 3834,\n/**/\n 3833,\n/**/\n 3832,\n/**/\n 3831,\n/**/\n 3830,\n/**/\n 3829,\n/**/\n 3828,\n/**/\n 3827,\n/**/\n 3826,\n/**/\n 3825,\n/**/\n 3824,\n/**/\n 3823,\n/**/\n 3822,\n/**/\n 3821,\n/**/\n 3820,\n/**/\n 3819,\n/**/\n 3818,\n/**/\n 3817,\n/**/\n 3816,\n/**/\n 3815,\n/**/\n 3814,\n/**/\n 3813,\n/**/\n 3812,\n/**/\n 3811,\n/**/\n 3810,\n/**/\n 3809,\n/**/\n 3808,\n/**/\n 3807,\n/**/\n 3806,\n/**/\n 3805,\n/**/\n 3804,\n/**/\n 3803,\n/**/\n 3802,\n/**/\n 3801,\n/**/\n 3800,\n/**/\n 3799,\n/**/\n 3798,\n/**/\n 3797,\n/**/\n 3796,\n/**/\n 3795,\n/**/\n 3794,\n/**/\n 3793,\n/**/\n 3792,\n/**/\n 3791,\n/**/\n 3790,\n/**/\n 3789,\n/**/\n 3788,\n/**/\n 3787,\n/**/\n 3786,\n/**/\n 3785,\n/**/\n 3784,\n/**/\n 3783,\n/**/\n 3782,\n/**/\n 3781,\n/**/\n 3780,\n/**/\n 3779,\n/**/\n 3778,\n/**/\n 3777,\n/**/\n 3776,\n/**/\n 3775,\n/**/\n 3774,\n/**/\n 3773,\n/**/\n 3772,\n/**/\n 3771,\n/**/\n 3770,\n/**/\n 3769,\n/**/\n 3768,\n/**/\n 3767,\n/**/\n 3766,\n/**/\n 3765,\n/**/\n 3764,\n/**/\n 3763,\n/**/\n 3762,\n/**/\n 3761,\n/**/\n 3760,\n/**/\n 3759,\n/**/\n 3758,\n/**/\n 3757,\n/**/\n 3756,\n/**/\n 3755,\n/**/\n 3754,\n/**/\n 3753,\n/**/\n 3752,\n/**/\n 3751,\n/**/\n 3750,\n/**/\n 3749,\n/**/\n 3748,\n/**/\n 3747,\n/**/\n 3746,\n/**/\n 3745,\n/**/\n 3744,\n/**/\n 3743,\n/**/\n 3742,\n/**/\n 3741,\n/**/\n 3740,\n/**/\n 3739,\n/**/\n 3738,\n/**/\n 3737,\n/**/\n 3736,\n/**/\n 3735,\n/**/\n 3734,\n/**/\n 3733,\n/**/\n 3732,\n/**/\n 3731,\n/**/\n 3730,\n/**/\n 3729,\n/**/\n 3728,\n/**/\n 3727,\n/**/\n 3726,\n/**/\n 3725,\n/**/\n 3724,\n/**/\n 3723,\n/**/\n 3722,\n/**/\n 3721,\n/**/\n 3720,\n/**/\n 3719,\n/**/\n 3718,\n/**/\n 3717,\n/**/\n 3716,\n/**/\n 3715,\n/**/\n 3714,\n/**/\n 3713,\n/**/\n 3712,\n/**/\n 3711,\n/**/\n 3710,\n/**/\n 3709,\n/**/\n 3708,\n/**/\n 3707,\n/**/\n 3706,\n/**/\n 3705,\n/**/\n 3704,\n/**/\n 3703,\n/**/\n 3702,\n/**/\n 3701,\n/**/\n 3700,\n/**/\n 3699,\n/**/\n 3698,\n/**/\n 3697,\n/**/\n 3696,\n/**/\n 3695,\n/**/\n 3694,\n/**/\n 3693,\n/**/\n 3692,\n/**/\n 3691,\n/**/\n 3690,\n/**/\n 3689,\n/**/\n 3688,\n/**/\n 3687,\n/**/\n 3686,\n/**/\n 3685,\n/**/\n 3684,\n/**/\n 3683,\n/**/\n 3682,\n/**/\n 3681,\n/**/\n 3680,\n/**/\n 3679,\n/**/\n 3678,\n/**/\n 3677,\n/**/\n 3676,\n/**/\n 3675,\n/**/\n 3674,\n/**/\n 3673,\n/**/\n 3672,\n/**/\n 3671,\n/**/\n 3670,\n/**/\n 3669,\n/**/\n 3668,\n/**/\n 3667,\n/**/\n 3666,\n/**/\n 3665,\n/**/\n 3664,\n/**/\n 3663,\n/**/\n 3662,\n/**/\n 3661,\n/**/\n 3660,\n/**/\n 3659,\n/**/\n 3658,\n/**/\n 3657,\n/**/\n 3656,\n/**/\n 3655,\n/**/\n 3654,\n/**/\n 3653,\n/**/\n 3652,\n/**/\n 3651,\n/**/\n 3650,\n/**/\n 3649,\n/**/\n 3648,\n/**/\n 3647,\n/**/\n 3646,\n/**/\n 3645,\n/**/\n 3644,\n/**/\n 3643,\n/**/\n 3642,\n/**/\n 3641,\n/**/\n 3640,\n/**/\n 3639,\n/**/\n 3638,\n/**/\n 3637,\n/**/\n 3636,\n/**/\n 3635,\n/**/\n 3634,\n/**/\n 3633,\n/**/\n 3632,\n/**/\n 3631,\n/**/\n 3630,\n/**/\n 3629,\n/**/\n 3628,\n/**/\n 3627,\n/**/\n 3626,\n/**/\n 3625,\n/**/\n 3624,\n/**/\n 3623,\n/**/\n 3622,\n/**/\n 3621,\n/**/\n 3620,\n/**/\n 3619,\n/**/\n 3618,\n/**/\n 3617,\n/**/\n 3616,\n/**/\n 3615,\n/**/\n 3614,\n/**/\n 3613,\n/**/\n 3612,\n/**/\n 3611,\n/**/\n 3610,\n/**/\n 3609,\n/**/\n 3608,\n/**/\n 3607,\n/**/\n 3606,\n/**/\n 3605,\n/**/\n 3604,\n/**/\n 3603,\n/**/\n 3602,\n/**/\n 3601,\n/**/\n 3600,\n/**/\n 3599,\n/**/\n 3598,\n/**/\n 3597,\n/**/\n 3596,\n/**/\n 3595,\n/**/\n 3594,\n/**/\n 3593,\n/**/\n 3592,\n/**/\n 3591,\n/**/\n 3590,\n/**/\n 3589,\n/**/\n 3588,\n/**/\n 3587,\n/**/\n 3586,\n/**/\n 3585,\n/**/\n 3584,\n/**/\n 3583,\n/**/\n 3582,\n/**/\n 3581,\n/**/\n 3580,\n/**/\n 3579,\n/**/\n 3578,\n/**/\n 3577,\n/**/\n 3576,\n/**/\n 3575,\n/**/\n 3574,\n/**/\n 3573,\n/**/\n 3572,\n/**/\n 3571,\n/**/\n 3570,\n/**/\n 3569,\n/**/\n 3568,\n/**/\n 3567,\n/**/\n 3566,\n/**/\n 3565,\n/**/\n 3564,\n/**/\n 3563,\n/**/\n 3562,\n/**/\n 3561,\n/**/\n 3560,\n/**/\n 3559,\n/**/\n 3558,\n/**/\n 3557,\n/**/\n 3556,\n/**/\n 3555,\n/**/\n 3554,\n/**/\n 3553,\n/**/\n 3552,\n/**/\n 3551,\n/**/\n 3550,\n/**/\n 3549,\n/**/\n 3548,\n/**/\n 3547,\n/**/\n 3546,\n/**/\n 3545,\n/**/\n 3544,\n/**/\n 3543,\n/**/\n 3542,\n/**/\n 3541,\n/**/\n 3540,\n/**/\n 3539,\n/**/\n 3538,\n/**/\n 3537,\n/**/\n 3536,\n/**/\n 3535,\n/**/\n 3534,\n/**/\n 3533,\n/**/\n 3532,\n/**/\n 3531,\n/**/\n 3530,\n/**/\n 3529,\n/**/\n 3528,\n/**/\n 3527,\n/**/\n 3526,\n/**/\n 3525,\n/**/\n 3524,\n/**/\n 3523,\n/**/\n 3522,\n/**/\n 3521,\n/**/\n 3520,\n/**/\n 3519,\n/**/\n 3518,\n/**/\n 3517,\n/**/\n 3516,\n/**/\n 3515,\n/**/\n 3514,\n/**/\n 3513,\n/**/\n 3512,\n/**/\n 3511,\n/**/\n 3510,\n/**/\n 3509,\n/**/\n 3508,\n/**/\n 3507,\n/**/\n 3506,\n/**/\n 3505,\n/**/\n 3504,\n/**/\n 3503,\n/**/\n 3502,\n/**/\n 3501,\n/**/\n 3500,\n/**/\n 3499,\n/**/\n 3498,\n/**/\n 3497,\n/**/\n 3496,\n/**/\n 3495,\n/**/\n 3494,\n/**/\n 3493,\n/**/\n 3492,\n/**/\n 3491,\n/**/\n 3490,\n/**/\n 3489,\n/**/\n 3488,\n/**/\n 3487,\n/**/\n 3486,\n/**/\n 3485,\n/**/\n 3484,\n/**/\n 3483,\n/**/\n 3482,\n/**/\n 3481,\n/**/\n 3480,\n/**/\n 3479,\n/**/\n 3478,\n/**/\n 3477,\n/**/\n 3476,\n/**/\n 3475,\n/**/\n 3474,\n/**/\n 3473,\n/**/\n 3472,\n/**/\n 3471,\n/**/\n 3470,\n/**/\n 3469,\n/**/\n 3468,\n/**/\n 3467,\n/**/\n 3466,\n/**/\n 3465,\n/**/\n 3464,\n/**/\n 3463,\n/**/\n 3462,\n/**/\n 3461,\n/**/\n 3460,\n/**/\n 3459,\n/**/\n 3458,\n/**/\n 3457,\n/**/\n 3456,\n/**/\n 3455,\n/**/\n 3454,\n/**/\n 3453,\n/**/\n 3452,\n/**/\n 3451,\n/**/\n 3450,\n/**/\n 3449,\n/**/\n 3448,\n/**/\n 3447,\n/**/\n 3446,\n/**/\n 3445,\n/**/\n 3444,\n/**/\n 3443,\n/**/\n 3442,\n/**/\n 3441,\n/**/\n 3440,\n/**/\n 3439,\n/**/\n 3438,\n/**/\n 3437,\n/**/\n 3436,\n/**/\n 3435,\n/**/\n 3434,\n/**/\n 3433,\n/**/\n 3432,\n/**/\n 3431,\n/**/\n 3430,\n/**/\n 3429,\n/**/\n 3428,\n/**/\n 3427,\n/**/\n 3426,\n/**/\n 3425,\n/**/\n 3424,\n/**/\n 3423,\n/**/\n 3422,\n/**/\n 3421,\n/**/\n 3420,\n/**/\n 3419,\n/**/\n 3418,\n/**/\n 3417,\n/**/\n 3416,\n/**/\n 3415,\n/**/\n 3414,\n/**/\n 3413,\n/**/\n 3412,\n/**/\n 3411,\n/**/\n 3410,\n/**/\n 3409,\n/**/\n 3408,\n/**/\n 3407,\n/**/\n 3406,\n/**/\n 3405,\n/**/\n 3404,\n/**/\n 3403,\n/**/\n 3402,\n/**/\n 3401,\n/**/\n 3400,\n/**/\n 3399,\n/**/\n 3398,\n/**/\n 3397,\n/**/\n 3396,\n/**/\n 3395,\n/**/\n 3394,\n/**/\n 3393,\n/**/\n 3392,\n/**/\n 3391,\n/**/\n 3390,\n/**/\n 3389,\n/**/\n 3388,\n/**/\n 3387,\n/**/\n 3386,\n/**/\n 3385,\n/**/\n 3384,\n/**/\n 3383,\n/**/\n 3382,\n/**/\n 3381,\n/**/\n 3380,\n/**/\n 3379,\n/**/\n 3378,\n/**/\n 3377,\n/**/\n 3376,\n/**/\n 3375,\n/**/\n 3374,\n/**/\n 3373,\n/**/\n 3372,\n/**/\n 3371,\n/**/\n 3370,\n/**/\n 3369,\n/**/\n 3368,\n/**/\n 3367,\n/**/\n 3366,\n/**/\n 3365,\n/**/\n 3364,\n/**/\n 3363,\n/**/\n 3362,\n/**/\n 3361,\n/**/\n 3360,\n/**/\n 3359,\n/**/\n 3358,\n/**/\n 3357,\n/**/\n 3356,\n/**/\n 3355,\n/**/\n 3354,\n/**/\n 3353,\n/**/\n 3352,\n/**/\n 3351,\n/**/\n 3350,\n/**/\n 3349,\n/**/\n 3348,\n/**/\n 3347,\n/**/\n 3346,\n/**/\n 3345,\n/**/\n 3344,\n/**/\n 3343,\n/**/\n 3342,\n/**/\n 3341,\n/**/\n 3340,\n/**/\n 3339,\n/**/\n 3338,\n/**/\n 3337,\n/**/\n 3336,\n/**/\n 3335,\n/**/\n 3334,\n/**/\n 3333,\n/**/\n 3332,\n/**/\n 3331,\n/**/\n 3330,\n/**/\n 3329,\n/**/\n 3328,\n/**/\n 3327,\n/**/\n 3326,\n/**/\n 3325,\n/**/\n 3324,\n/**/\n 3323,\n/**/\n 3322,\n/**/\n 3321,\n/**/\n 3320,\n/**/\n 3319,\n/**/\n 3318,\n/**/\n 3317,\n/**/\n 3316,\n/**/\n 3315,\n/**/\n 3314,\n/**/\n 3313,\n/**/\n 3312,\n/**/\n 3311,\n/**/\n 3310,\n/**/\n 3309,\n/**/\n 3308,\n/**/\n 3307,\n/**/\n 3306,\n/**/\n 3305,\n/**/\n 3304,\n/**/\n 3303,\n/**/\n 3302,\n/**/\n 3301,\n/**/\n 3300,\n/**/\n 3299,\n/**/\n 3298,\n/**/\n 3297,\n/**/\n 3296,\n/**/\n 3295,\n/**/\n 3294,\n/**/\n 3293,\n/**/\n 3292,\n/**/\n 3291,\n/**/\n 3290,\n/**/\n 3289,\n/**/\n 3288,\n/**/\n 3287,\n/**/\n 3286,\n/**/\n 3285,\n/**/\n 3284,\n/**/\n 3283,\n/**/\n 3282,\n/**/\n 3281,\n/**/\n 3280,\n/**/\n 3279,\n/**/\n 3278,\n/**/\n 3277,\n/**/\n 3276,\n/**/\n 3275,\n/**/\n 3274,\n/**/\n 3273,\n/**/\n 3272,\n/**/\n 3271,\n/**/\n 3270,\n/**/\n 3269,\n/**/\n 3268,\n/**/\n 3267,\n/**/\n 3266,\n/**/\n 3265,\n/**/\n 3264,\n/**/\n 3263,\n/**/\n 3262,\n/**/\n 3261,\n/**/\n 3260,\n/**/\n 3259,\n/**/\n 3258,\n/**/\n 3257,\n/**/\n 3256,\n/**/\n 3255,\n/**/\n 3254,\n/**/\n 3253,\n/**/\n 3252,\n/**/\n 3251,\n/**/\n 3250,\n/**/\n 3249,\n/**/\n 3248,\n/**/\n 3247,\n/**/\n 3246,\n/**/\n 3245,\n/**/\n 3244,\n/**/\n 3243,\n/**/\n 3242,\n/**/\n 3241,\n/**/\n 3240,\n/**/\n 3239,\n/**/\n 3238,\n/**/\n 3237,\n/**/\n 3236,\n/**/\n 3235,\n/**/\n 3234,\n/**/\n 3233,\n/**/\n 3232,\n/**/\n 3231,\n/**/\n 3230,\n/**/\n 3229,\n/**/\n 3228,\n/**/\n 3227,\n/**/\n 3226,\n/**/\n 3225,\n/**/\n 3224,\n/**/\n 3223,\n/**/\n 3222,\n/**/\n 3221,\n/**/\n 3220,\n/**/\n 3219,\n/**/\n 3218,\n/**/\n 3217,\n/**/\n 3216,\n/**/\n 3215,\n/**/\n 3214,\n/**/\n 3213,\n/**/\n 3212,\n/**/\n 3211,\n/**/\n 3210,\n/**/\n 3209,\n/**/\n 3208,\n/**/\n 3207,\n/**/\n 3206,\n/**/\n 3205,\n/**/\n 3204,\n/**/\n 3203,\n/**/\n 3202,\n/**/\n 3201,\n/**/\n 3200,\n/**/\n 3199,\n/**/\n 3198,\n/**/\n 3197,\n/**/\n 3196,\n/**/\n 3195,\n/**/\n 3194,\n/**/\n 3193,\n/**/\n 3192,\n/**/\n 3191,\n/**/\n 3190,\n/**/\n 3189,\n/**/\n 3188,\n/**/\n 3187,\n/**/\n 3186,\n/**/\n 3185,\n/**/\n 3184,\n/**/\n 3183,\n/**/\n 3182,\n/**/\n 3181,\n/**/\n 3180,\n/**/\n 3179,\n/**/\n 3178,\n/**/\n 3177,\n/**/\n 3176,\n/**/\n 3175,\n/**/\n 3174,\n/**/\n 3173,\n/**/\n 3172,\n/**/\n 3171,\n/**/\n 3170,\n/**/\n 3169,\n/**/\n 3168,\n/**/\n 3167,\n/**/\n 3166,\n/**/\n 3165,\n/**/\n 3164,\n/**/\n 3163,\n/**/\n 3162,\n/**/\n 3161,\n/**/\n 3160,\n/**/\n 3159,\n/**/\n 3158,\n/**/\n 3157,\n/**/\n 3156,\n/**/\n 3155,\n/**/\n 3154,\n/**/\n 3153,\n/**/\n 3152,\n/**/\n 3151,\n/**/\n 3150,\n/**/\n 3149,\n/**/\n 3148,\n/**/\n 3147,\n/**/\n 3146,\n/**/\n 3145,\n/**/\n 3144,\n/**/\n 3143,\n/**/\n 3142,\n/**/\n 3141,\n/**/\n 3140,\n/**/\n 3139,\n/**/\n 3138,\n/**/\n 3137,\n/**/\n 3136,\n/**/\n 3135,\n/**/\n 3134,\n/**/\n 3133,\n/**/\n 3132,\n/**/\n 3131,\n/**/\n 3130,\n/**/\n 3129,\n/**/\n 3128,\n/**/\n 3127,\n/**/\n 3126,\n/**/\n 3125,\n/**/\n 3124,\n/**/\n 3123,\n/**/\n 3122,\n/**/\n 3121,\n/**/\n 3120,\n/**/\n 3119,\n/**/\n 3118,\n/**/\n 3117,\n/**/\n 3116,\n/**/\n 3115,\n/**/\n 3114,\n/**/\n 3113,\n/**/\n 3112,\n/**/\n 3111,\n/**/\n 3110,\n/**/\n 3109,\n/**/\n 3108,\n/**/\n 3107,\n/**/\n 3106,\n/**/\n 3105,\n/**/\n 3104,\n/**/\n 3103,\n/**/\n 3102,\n/**/\n 3101,\n/**/\n 3100,\n/**/\n 3099,\n/**/\n 3098,\n/**/\n 3097,\n/**/\n 3096,\n/**/\n 3095,\n/**/\n 3094,\n/**/\n 3093,\n/**/\n 3092,\n/**/\n 3091,\n/**/\n 3090,\n/**/\n 3089,\n/**/\n 3088,\n/**/\n 3087,\n/**/\n 3086,\n/**/\n 3085,\n/**/\n 3084,\n/**/\n 3083,\n/**/\n 3082,\n/**/\n 3081,\n/**/\n 3080,\n/**/\n 3079,\n/**/\n 3078,\n/**/\n 3077,\n/**/\n 3076,\n/**/\n 3075,\n/**/\n 3074,\n/**/\n 3073,\n/**/\n 3072,\n/**/\n 3071,\n/**/\n 3070,\n/**/\n 3069,\n/**/\n 3068,\n/**/\n 3067,\n/**/\n 3066,\n/**/\n 3065,\n/**/\n 3064,\n/**/\n 3063,\n/**/\n 3062,\n/**/\n 3061,\n/**/\n 3060,\n/**/\n 3059,\n/**/\n 3058,\n/**/\n 3057,\n/**/\n 3056,\n/**/\n 3055,\n/**/\n 3054,\n/**/\n 3053,\n/**/\n 3052,\n/**/\n 3051,\n/**/\n 3050,\n/**/\n 3049,\n/**/\n 3048,\n/**/\n 3047,\n/**/\n 3046,\n/**/\n 3045,\n/**/\n 3044,\n/**/\n 3043,\n/**/\n 3042,\n/**/\n 3041,\n/**/\n 3040,\n/**/\n 3039,\n/**/\n 3038,\n/**/\n 3037,\n/**/\n 3036,\n/**/\n 3035,\n/**/\n 3034,\n/**/\n 3033,\n/**/\n 3032,\n/**/\n 3031,\n/**/\n 3030,\n/**/\n 3029,\n/**/\n 3028,\n/**/\n 3027,\n/**/\n 3026,\n/**/\n 3025,\n/**/\n 3024,\n/**/\n 3023,\n/**/\n 3022,\n/**/\n 3021,\n/**/\n 3020,\n/**/\n 3019,\n/**/\n 3018,\n/**/\n 3017,\n/**/\n 3016,\n/**/\n 3015,\n/**/\n 3014,\n/**/\n 3013,\n/**/\n 3012,\n/**/\n 3011,\n/**/\n 3010,\n/**/\n 3009,\n/**/\n 3008,\n/**/\n 3007,\n/**/\n 3006,\n/**/\n 3005,\n/**/\n 3004,\n/**/\n 3003,\n/**/\n 3002,\n/**/\n 3001,\n/**/\n 3000,\n/**/\n 2999,\n/**/\n 2998,\n/**/\n 2997,\n/**/\n 2996,\n/**/\n 2995,\n/**/\n 2994,\n/**/\n 2993,\n/**/\n 2992,\n/**/\n 2991,\n/**/\n 2990,\n/**/\n 2989,\n/**/\n 2988,\n/**/\n 2987,\n/**/\n 2986,\n/**/\n 2985,\n/**/\n 2984,\n/**/\n 2983,\n/**/\n 2982,\n/**/\n 2981,\n/**/\n 2980,\n/**/\n 2979,\n/**/\n 2978,\n/**/\n 2977,\n/**/\n 2976,\n/**/\n 2975,\n/**/\n 2974,\n/**/\n 2973,\n/**/\n 2972,\n/**/\n 2971,\n/**/\n 2970,\n/**/\n 2969,\n/**/\n 2968,\n/**/\n 2967,\n/**/\n 2966,\n/**/\n 2965,\n/**/\n 2964,\n/**/\n 2963,\n/**/\n 2962,\n/**/\n 2961,\n/**/\n 2960,\n/**/\n 2959,\n/**/\n 2958,\n/**/\n 2957,\n/**/\n 2956,\n/**/\n 2955,\n/**/\n 2954,\n/**/\n 2953,\n/**/\n 2952,\n/**/\n 2951,\n/**/\n 2950,\n/**/\n 2949,\n/**/\n 2948,\n/**/\n 2947,\n/**/\n 2946,\n/**/\n 2945,\n/**/\n 2944,\n/**/\n 2943,\n/**/\n 2942,\n/**/\n 2941,\n/**/\n 2940,\n/**/\n 2939,\n/**/\n 2938,\n/**/\n 2937,\n/**/\n 2936,\n/**/\n 2935,\n/**/\n 2934,\n/**/\n 2933,\n/**/\n 2932,\n/**/\n 2931,\n/**/\n 2930,\n/**/\n 2929,\n/**/\n 2928,\n/**/\n 2927,\n/**/\n 2926,\n/**/\n 2925,\n/**/\n 2924,\n/**/\n 2923,\n/**/\n 2922,\n/**/\n 2921,\n/**/\n 2920,\n/**/\n 2919,\n/**/\n 2918,\n/**/\n 2917,\n/**/\n 2916,\n/**/\n 2915,\n/**/\n 2914,\n/**/\n 2913,\n/**/\n 2912,\n/**/\n 2911,\n/**/\n 2910,\n/**/\n 2909,\n/**/\n 2908,\n/**/\n 2907,\n/**/\n 2906,\n/**/\n 2905,\n/**/\n 2904,\n/**/\n 2903,\n/**/\n 2902,\n/**/\n 2901,\n/**/\n 2900,\n/**/\n 2899,\n/**/\n 2898,\n/**/\n 2897,\n/**/\n 2896,\n/**/\n 2895,\n/**/\n 2894,\n/**/\n 2893,\n/**/\n 2892,\n/**/\n 2891,\n/**/\n 2890,\n/**/\n 2889,\n/**/\n 2888,\n/**/\n 2887,\n/**/\n 2886,\n/**/\n 2885,\n/**/\n 2884,\n/**/\n 2883,\n/**/\n 2882,\n/**/\n 2881,\n/**/\n 2880,\n/**/\n 2879,\n/**/\n 2878,\n/**/\n 2877,\n/**/\n 2876,\n/**/\n 2875,\n/**/\n 2874,\n/**/\n 2873,\n/**/\n 2872,\n/**/\n 2871,\n/**/\n 2870,\n/**/\n 2869,\n/**/\n 2868,\n/**/\n 2867,\n/**/\n 2866,\n/**/\n 2865,\n/**/\n 2864,\n/**/\n 2863,\n/**/\n 2862,\n/**/\n 2861,\n/**/\n 2860,\n/**/\n 2859,\n/**/\n 2858,\n/**/\n 2857,\n/**/\n 2856,\n/**/\n 2855,\n/**/\n 2854,\n/**/\n 2853,\n/**/\n 2852,\n/**/\n 2851,\n/**/\n 2850,\n/**/\n 2849,\n/**/\n 2848,\n/**/\n 2847,\n/**/\n 2846,\n/**/\n 2845,\n/**/\n 2844,\n/**/\n 2843,\n/**/\n 2842,\n/**/\n 2841,\n/**/\n 2840,\n/**/\n 2839,\n/**/\n 2838,\n/**/\n 2837,\n/**/\n 2836,\n/**/\n 2835,\n/**/\n 2834,\n/**/\n 2833,\n/**/\n 2832,\n/**/\n 2831,\n/**/\n 2830,\n/**/\n 2829,\n/**/\n 2828,\n/**/\n 2827,\n/**/\n 2826,\n/**/\n 2825,\n/**/\n 2824,\n/**/\n 2823,\n/**/\n 2822,\n/**/\n 2821,\n/**/\n 2820,\n/**/\n 2819,\n/**/\n 2818,\n/**/\n 2817,\n/**/\n 2816,\n/**/\n 2815,\n/**/\n 2814,\n/**/\n 2813,\n/**/\n 2812,\n/**/\n 2811,\n/**/\n 2810,\n/**/\n 2809,\n/**/\n 2808,\n/**/\n 2807,\n/**/\n 2806,\n/**/\n 2805,\n/**/\n 2804,\n/**/\n 2803,\n/**/\n 2802,\n/**/\n 2801,\n/**/\n 2800,\n/**/\n 2799,\n/**/\n 2798,\n/**/\n 2797,\n/**/\n 2796,\n/**/\n 2795,\n/**/\n 2794,\n/**/\n 2793,\n/**/\n 2792,\n/**/\n 2791,\n/**/\n 2790,\n/**/\n 2789,\n/**/\n 2788,\n/**/\n 2787,\n/**/\n 2786,\n/**/\n 2785,\n/**/\n 2784,\n/**/\n 2783,\n/**/\n 2782,\n/**/\n 2781,\n/**/\n 2780,\n/**/\n 2779,\n/**/\n 2778,\n/**/\n 2777,\n/**/\n 2776,\n/**/\n 2775,\n/**/\n 2774,\n/**/\n 2773,\n/**/\n 2772,\n/**/\n 2771,\n/**/\n 2770,\n/**/\n 2769,\n/**/\n 2768,\n/**/\n 2767,\n/**/\n 2766,\n/**/\n 2765,\n/**/\n 2764,\n/**/\n 2763,\n/**/\n 2762,\n/**/\n 2761,\n/**/\n 2760,\n/**/\n 2759,\n/**/\n 2758,\n/**/\n 2757,\n/**/\n 2756,\n/**/\n 2755,\n/**/\n 2754,\n/**/\n 2753,\n/**/\n 2752,\n/**/\n 2751,\n/**/\n 2750,\n/**/\n 2749,\n/**/\n 2748,\n/**/\n 2747,\n/**/\n 2746,\n/**/\n 2745,\n/**/\n 2744,\n/**/\n 2743,\n/**/\n 2742,\n/**/\n 2741,\n/**/\n 2740,\n/**/\n 2739,\n/**/\n 2738,\n/**/\n 2737,\n/**/\n 2736,\n/**/\n 2735,\n/**/\n 2734,\n/**/\n 2733,\n/**/\n 2732,\n/**/\n 2731,\n/**/\n 2730,\n/**/\n 2729,\n/**/\n 2728,\n/**/\n 2727,\n/**/\n 2726,\n/**/\n 2725,\n/**/\n 2724,\n/**/\n 2723,\n/**/\n 2722,\n/**/\n 2721,\n/**/\n 2720,\n/**/\n 2719,\n/**/\n 2718,\n/**/\n 2717,\n/**/\n 2716,\n/**/\n 2715,\n/**/\n 2714,\n/**/\n 2713,\n/**/\n 2712,\n/**/\n 2711,\n/**/\n 2710,\n/**/\n 2709,\n/**/\n 2708,\n/**/\n 2707,\n/**/\n 2706,\n/**/\n 2705,\n/**/\n 2704,\n/**/\n 2703,\n/**/\n 2702,\n/**/\n 2701,\n/**/\n 2700,\n/**/\n 2699,\n/**/\n 2698,\n/**/\n 2697,\n/**/\n 2696,\n/**/\n 2695,\n/**/\n 2694,\n/**/\n 2693,\n/**/\n 2692,\n/**/\n 2691,\n/**/\n 2690,\n/**/\n 2689,\n/**/\n 2688,\n/**/\n 2687,\n/**/\n 2686,\n/**/\n 2685,\n/**/\n 2684,\n/**/\n 2683,\n/**/\n 2682,\n/**/\n 2681,\n/**/\n 2680,\n/**/\n 2679,\n/**/\n 2678,\n/**/\n 2677,\n/**/\n 2676,\n/**/\n 2675,\n/**/\n 2674,\n/**/\n 2673,\n/**/\n 2672,\n/**/\n 2671,\n/**/\n 2670,\n/**/\n 2669,\n/**/\n 2668,\n/**/\n 2667,\n/**/\n 2666,\n/**/\n 2665,\n/**/\n 2664,\n/**/\n 2663,\n/**/\n 2662,\n/**/\n 2661,\n/**/\n 2660,\n/**/\n 2659,\n/**/\n 2658,\n/**/\n 2657,\n/**/\n 2656,\n/**/\n 2655,\n/**/\n 2654,\n/**/\n 2653,\n/**/\n 2652,\n/**/\n 2651,\n/**/\n 2650,\n/**/\n 2649,\n/**/\n 2648,\n/**/\n 2647,\n/**/\n 2646,\n/**/\n 2645,\n/**/\n 2644,\n/**/\n 2643,\n/**/\n 2642,\n/**/\n 2641,\n/**/\n 2640,\n/**/\n 2639,\n/**/\n 2638,\n/**/\n 2637,\n/**/\n 2636,\n/**/\n 2635,\n/**/\n 2634,\n/**/\n 2633,\n/**/\n 2632,\n/**/\n 2631,\n/**/\n 2630,\n/**/\n 2629,\n/**/\n 2628,\n/**/\n 2627,\n/**/\n 2626,\n/**/\n 2625,\n/**/\n 2624,\n/**/\n 2623,\n/**/\n 2622,\n/**/\n 2621,\n/**/\n 2620,\n/**/\n 2619,\n/**/\n 2618,\n/**/\n 2617,\n/**/\n 2616,\n/**/\n 2615,\n/**/\n 2614,\n/**/\n 2613,\n/**/\n 2612,\n/**/\n 2611,\n/**/\n 2610,\n/**/\n 2609,\n/**/\n 2608,\n/**/\n 2607,\n/**/\n 2606,\n/**/\n 2605,\n/**/\n 2604,\n/**/\n 2603,\n/**/\n 2602,\n/**/\n 2601,\n/**/\n 2600,\n/**/\n 2599,\n/**/\n 2598,\n/**/\n 2597,\n/**/\n 2596,\n/**/\n 2595,\n/**/\n 2594,\n/**/\n 2593,\n/**/\n 2592,\n/**/\n 2591,\n/**/\n 2590,\n/**/\n 2589,\n/**/\n 2588,\n/**/\n 2587,\n/**/\n 2586,\n/**/\n 2585,\n/**/\n 2584,\n/**/\n 2583,\n/**/\n 2582,\n/**/\n 2581,\n/**/\n 2580,\n/**/\n 2579,\n/**/\n 2578,\n/**/\n 2577,\n/**/\n 2576,\n/**/\n 2575,\n/**/\n 2574,\n/**/\n 2573,\n/**/\n 2572,\n/**/\n 2571,\n/**/\n 2570,\n/**/\n 2569,\n/**/\n 2568,\n/**/\n 2567,\n/**/\n 2566,\n/**/\n 2565,\n/**/\n 2564,\n/**/\n 2563,\n/**/\n 2562,\n/**/\n 2561,\n/**/\n 2560,\n/**/\n 2559,\n/**/\n 2558,\n/**/\n 2557,\n/**/\n 2556,\n/**/\n 2555,\n/**/\n 2554,\n/**/\n 2553,\n/**/\n 2552,\n/**/\n 2551,\n/**/\n 2550,\n/**/\n 2549,\n/**/\n 2548,\n/**/\n 2547,\n/**/\n 2546,\n/**/\n 2545,\n/**/\n 2544,\n/**/\n 2543,\n/**/\n 2542,\n/**/\n 2541,\n/**/\n 2540,\n/**/\n 2539,\n/**/\n 2538,\n/**/\n 2537,\n/**/\n 2536,\n/**/\n 2535,\n/**/\n 2534,\n/**/\n 2533,\n/**/\n 2532,\n/**/\n 2531,\n/**/\n 2530,\n/**/\n 2529,\n/**/\n 2528,\n/**/\n 2527,\n/**/\n 2526,\n/**/\n 2525,\n/**/\n 2524,\n/**/\n 2523,\n/**/\n 2522,\n/**/\n 2521,\n/**/\n 2520,\n/**/\n 2519,\n/**/\n 2518,\n/**/\n 2517,\n/**/\n 2516,\n/**/\n 2515,\n/**/\n 2514,\n/**/\n 2513,\n/**/\n 2512,\n/**/\n 2511,\n/**/\n 2510,\n/**/\n 2509,\n/**/\n 2508,\n/**/\n 2507,\n/**/\n 2506,\n/**/\n 2505,\n/**/\n 2504,\n/**/\n 2503,\n/**/\n 2502,\n/**/\n 2501,\n/**/\n 2500,\n/**/\n 2499,\n/**/\n 2498,\n/**/\n 2497,\n/**/\n 2496,\n/**/\n 2495,\n/**/\n 2494,\n/**/\n 2493,\n/**/\n 2492,\n/**/\n 2491,\n/**/\n 2490,\n/**/\n 2489,\n/**/\n 2488,\n/**/\n 2487,\n/**/\n 2486,\n/**/\n 2485,\n/**/\n 2484,\n/**/\n 2483,\n/**/\n 2482,\n/**/\n 2481,\n/**/\n 2480,\n/**/\n 2479,\n/**/\n 2478,\n/**/\n 2477,\n/**/\n 2476,\n/**/\n 2475,\n/**/\n 2474,\n/**/\n 2473,\n/**/\n 2472,\n/**/\n 2471,\n/**/\n 2470,\n/**/\n 2469,\n/**/\n 2468,\n/**/\n 2467,\n/**/\n 2466,\n/**/\n 2465,\n/**/\n 2464,\n/**/\n 2463,\n/**/\n 2462,\n/**/\n 2461,\n/**/\n 2460,\n/**/\n 2459,\n/**/\n 2458,\n/**/\n 2457,\n/**/\n 2456,\n/**/\n 2455,\n/**/\n 2454,\n/**/\n 2453,\n/**/\n 2452,\n/**/\n 2451,\n/**/\n 2450,\n/**/\n 2449,\n/**/\n 2448,\n/**/\n 2447,\n/**/\n 2446,\n/**/\n 2445,\n/**/\n 2444,\n/**/\n 2443,\n/**/\n 2442,\n/**/\n 2441,\n/**/\n 2440,\n/**/\n 2439,\n/**/\n 2438,\n/**/\n 2437,\n/**/\n 2436,\n/**/\n 2435,\n/**/\n 2434,\n/**/\n 2433,\n/**/\n 2432,\n/**/\n 2431,\n/**/\n 2430,\n/**/\n 2429,\n/**/\n 2428,\n/**/\n 2427,\n/**/\n 2426,\n/**/\n 2425,\n/**/\n 2424,\n/**/\n 2423,\n/**/\n 2422,\n/**/\n 2421,\n/**/\n 2420,\n/**/\n 2419,\n/**/\n 2418,\n/**/\n 2417,\n/**/\n 2416,\n/**/\n 2415,\n/**/\n 2414,\n/**/\n 2413,\n/**/\n 2412,\n/**/\n 2411,\n/**/\n 2410,\n/**/\n 2409,\n/**/\n 2408,\n/**/\n 2407,\n/**/\n 2406,\n/**/\n 2405,\n/**/\n 2404,\n/**/\n 2403,\n/**/\n 2402,\n/**/\n 2401,\n/**/\n 2400,\n/**/\n 2399,\n/**/\n 2398,\n/**/\n 2397,\n/**/\n 2396,\n/**/\n 2395,\n/**/\n 2394,\n/**/\n 2393,\n/**/\n 2392,\n/**/\n 2391,\n/**/\n 2390,\n/**/\n 2389,\n/**/\n 2388,\n/**/\n 2387,\n/**/\n 2386,\n/**/\n 2385,\n/**/\n 2384,\n/**/\n 2383,\n/**/\n 2382,\n/**/\n 2381,\n/**/\n 2380,\n/**/\n 2379,\n/**/\n 2378,\n/**/\n 2377,\n/**/\n 2376,\n/**/\n 2375,\n/**/\n 2374,\n/**/\n 2373,\n/**/\n 2372,\n/**/\n 2371,\n/**/\n 2370,\n/**/\n 2369,\n/**/\n 2368,\n/**/\n 2367,\n/**/\n 2366,\n/**/\n 2365,\n/**/\n 2364,\n/**/\n 2363,\n/**/\n 2362,\n/**/\n 2361,\n/**/\n 2360,\n/**/\n 2359,\n/**/\n 2358,\n/**/\n 2357,\n/**/\n 2356,\n/**/\n 2355,\n/**/\n 2354,\n/**/\n 2353,\n/**/\n 2352,\n/**/\n 2351,\n/**/\n 2350,\n/**/\n 2349,\n/**/\n 2348,\n/**/\n 2347,\n/**/\n 2346,\n/**/\n 2345,\n/**/\n 2344,\n/**/\n 2343,\n/**/\n 2342,\n/**/\n 2341,\n/**/\n 2340,\n/**/\n 2339,\n/**/\n 2338,\n/**/\n 2337,\n/**/\n 2336,\n/**/\n 2335,\n/**/\n 2334,\n/**/\n 2333,\n/**/\n 2332,\n/**/\n 2331,\n/**/\n 2330,\n/**/\n 2329,\n/**/\n 2328,\n/**/\n 2327,\n/**/\n 2326,\n/**/\n 2325,\n/**/\n 2324,\n/**/\n 2323,\n/**/\n 2322,\n/**/\n 2321,\n/**/\n 2320,\n/**/\n 2319,\n/**/\n 2318,\n/**/\n 2317,\n/**/\n 2316,\n/**/\n 2315,\n/**/\n 2314,\n/**/\n 2313,\n/**/\n 2312,\n/**/\n 2311,\n/**/\n 2310,\n/**/\n 2309,\n/**/\n 2308,\n/**/\n 2307,\n/**/\n 2306,\n/**/\n 2305,\n/**/\n 2304,\n/**/\n 2303,\n/**/\n 2302,\n/**/\n 2301,\n/**/\n 2300,\n/**/\n 2299,\n/**/\n 2298,\n/**/\n 2297,\n/**/\n 2296,\n/**/\n 2295,\n/**/\n 2294,\n/**/\n 2293,\n/**/\n 2292,\n/**/\n 2291,\n/**/\n 2290,\n/**/\n 2289,\n/**/\n 2288,\n/**/\n 2287,\n/**/\n 2286,\n/**/\n 2285,\n/**/\n 2284,\n/**/\n 2283,\n/**/\n 2282,\n/**/\n 2281,\n/**/\n 2280,\n/**/\n 2279,\n/**/\n 2278,\n/**/\n 2277,\n/**/\n 2276,\n/**/\n 2275,\n/**/\n 2274,\n/**/\n 2273,\n/**/\n 2272,\n/**/\n 2271,\n/**/\n 2270,\n/**/\n 2269,\n/**/\n 2268,\n/**/\n 2267,\n/**/\n 2266,\n/**/\n 2265,\n/**/\n 2264,\n/**/\n 2263,\n/**/\n 2262,\n/**/\n 2261,\n/**/\n 2260,\n/**/\n 2259,\n/**/\n 2258,\n/**/\n 2257,\n/**/\n 2256,\n/**/\n 2255,\n/**/\n 2254,\n/**/\n 2253,\n/**/\n 2252,\n/**/\n 2251,\n/**/\n 2250,\n/**/\n 2249,\n/**/\n 2248,\n/**/\n 2247,\n/**/\n 2246,\n/**/\n 2245,\n/**/\n 2244,\n/**/\n 2243,\n/**/\n 2242,\n/**/\n 2241,\n/**/\n 2240,\n/**/\n 2239,\n/**/\n 2238,\n/**/\n 2237,\n/**/\n 2236,\n/**/\n 2235,\n/**/\n 2234,\n/**/\n 2233,\n/**/\n 2232,\n/**/\n 2231,\n/**/\n 2230,\n/**/\n 2229,\n/**/\n 2228,\n/**/\n 2227,\n/**/\n 2226,\n/**/\n 2225,\n/**/\n 2224,\n/**/\n 2223,\n/**/\n 2222,\n/**/\n 2221,\n/**/\n 2220,\n/**/\n 2219,\n/**/\n 2218,\n/**/\n 2217,\n/**/\n 2216,\n/**/\n 2215,\n/**/\n 2214,\n/**/\n 2213,\n/**/\n 2212,\n/**/\n 2211,\n/**/\n 2210,\n/**/\n 2209,\n/**/\n 2208,\n/**/\n 2207,\n/**/\n 2206,\n/**/\n 2205,\n/**/\n 2204,\n/**/\n 2203,\n/**/\n 2202,\n/**/\n 2201,\n/**/\n 2200,\n/**/\n 2199,\n/**/\n 2198,\n/**/\n 2197,\n/**/\n 2196,\n/**/\n 2195,\n/**/\n 2194,\n/**/\n 2193,\n/**/\n 2192,\n/**/\n 2191,\n/**/\n 2190,\n/**/\n 2189,\n/**/\n 2188,\n/**/\n 2187,\n/**/\n 2186,\n/**/\n 2185,\n/**/\n 2184,\n/**/\n 2183,\n/**/\n 2182,\n/**/\n 2181,\n/**/\n 2180,\n/**/\n 2179,\n/**/\n 2178,\n/**/\n 2177,\n/**/\n 2176,\n/**/\n 2175,\n/**/\n 2174,\n/**/\n 2173,\n/**/\n 2172,\n/**/\n 2171,\n/**/\n 2170,\n/**/\n 2169,\n/**/\n 2168,\n/**/\n 2167,\n/**/\n 2166,\n/**/\n 2165,\n/**/\n 2164,\n/**/\n 2163,\n/**/\n 2162,\n/**/\n 2161,\n/**/\n 2160,\n/**/\n 2159,\n/**/\n 2158,\n/**/\n 2157,\n/**/\n 2156,\n/**/\n 2155,\n/**/\n 2154,\n/**/\n 2153,\n/**/\n 2152,\n/**/\n 2151,\n/**/\n 2150,\n/**/\n 2149,\n/**/\n 2148,\n/**/\n 2147,\n/**/\n 2146,\n/**/\n 2145,\n/**/\n 2144,\n/**/\n 2143,\n/**/\n 2142,\n/**/\n 2141,\n/**/\n 2140,\n/**/\n 2139,\n/**/\n 2138,\n/**/\n 2137,\n/**/\n 2136,\n/**/\n 2135,\n/**/\n 2134,\n/**/\n 2133,\n/**/\n 2132,\n/**/\n 2131,\n/**/\n 2130,\n/**/\n 2129,\n/**/\n 2128,\n/**/\n 2127,\n/**/\n 2126,\n/**/\n 2125,\n/**/\n 2124,\n/**/\n 2123,\n/**/\n 2122,\n/**/\n 2121,\n/**/\n 2120,\n/**/\n 2119,\n/**/\n 2118,\n/**/\n 2117,\n/**/\n 2116,\n/**/\n 2115,\n/**/\n 2114,\n/**/\n 2113,\n/**/\n 2112,\n/**/\n 2111,\n/**/\n 2110,\n/**/\n 2109,\n/**/\n 2108,\n/**/\n 2107,\n/**/\n 2106,\n/**/\n 2105,\n/**/\n 2104,\n/**/\n 2103,\n/**/\n 2102,\n/**/\n 2101,\n/**/\n 2100,\n/**/\n 2099,\n/**/\n 2098,\n/**/\n 2097,\n/**/\n 2096,\n/**/\n 2095,\n/**/\n 2094,\n/**/\n 2093,\n/**/\n 2092,\n/**/\n 2091,\n/**/\n 2090,\n/**/\n 2089,\n/**/\n 2088,\n/**/\n 2087,\n/**/\n 2086,\n/**/\n 2085,\n/**/\n 2084,\n/**/\n 2083,\n/**/\n 2082,\n/**/\n 2081,\n/**/\n 2080,\n/**/\n 2079,\n/**/\n 2078,\n/**/\n 2077,\n/**/\n 2076,\n/**/\n 2075,\n/**/\n 2074,\n/**/\n 2073,\n/**/\n 2072,\n/**/\n 2071,\n/**/\n 2070,\n/**/\n 2069,\n/**/\n 2068,\n/**/\n 2067,\n/**/\n 2066,\n/**/\n 2065,\n/**/\n 2064,\n/**/\n 2063,\n/**/\n 2062,\n/**/\n 2061,\n/**/\n 2060,\n/**/\n 2059,\n/**/\n 2058,\n/**/\n 2057,\n/**/\n 2056,\n/**/\n 2055,\n/**/\n 2054,\n/**/\n 2053,\n/**/\n 2052,\n/**/\n 2051,\n/**/\n 2050,\n/**/\n 2049,\n/**/\n 2048,\n/**/\n 2047,\n/**/\n 2046,\n/**/\n 2045,\n/**/\n 2044,\n/**/\n 2043,\n/**/\n 2042,\n/**/\n 2041,\n/**/\n 2040,\n/**/\n 2039,\n/**/\n 2038,\n/**/\n 2037,\n/**/\n 2036,\n/**/\n 2035,\n/**/\n 2034,\n/**/\n 2033,\n/**/\n 2032,\n/**/\n 2031,\n/**/\n 2030,\n/**/\n 2029,\n/**/\n 2028,\n/**/\n 2027,\n/**/\n 2026,\n/**/\n 2025,\n/**/\n 2024,\n/**/\n 2023,\n/**/\n 2022,\n/**/\n 2021,\n/**/\n 2020,\n/**/\n 2019,\n/**/\n 2018,\n/**/\n 2017,\n/**/\n 2016,\n/**/\n 2015,\n/**/\n 2014,\n/**/\n 2013,\n/**/\n 2012,\n/**/\n 2011,\n/**/\n 2010,\n/**/\n 2009,\n/**/\n 2008,\n/**/\n 2007,\n/**/\n 2006,\n/**/\n 2005,\n/**/\n 2004,\n/**/\n 2003,\n/**/\n 2002,\n/**/\n 2001,\n/**/\n 2000,\n/**/\n 1999,\n/**/\n 1998,\n/**/\n 1997,\n/**/\n 1996,\n/**/\n 1995,\n/**/\n 1994,\n/**/\n 1993,\n/**/\n 1992,\n/**/\n 1991,\n/**/\n 1990,\n/**/\n 1989,\n/**/\n 1988,\n/**/\n 1987,\n/**/\n 1986,\n/**/\n 1985,\n/**/\n 1984,\n/**/\n 1983,\n/**/\n 1982,\n/**/\n 1981,\n/**/\n 1980,\n/**/\n 1979,\n/**/\n 1978,\n/**/\n 1977,\n/**/\n 1976,\n/**/\n 1975,\n/**/\n 1974,\n/**/\n 1973,\n/**/\n 1972,\n/**/\n 1971,\n/**/\n 1970,\n/**/\n 1969,\n/**/\n 1968,\n/**/\n 1967,\n/**/\n 1966,\n/**/\n 1965,\n/**/\n 1964,\n/**/\n 1963,\n/**/\n 1962,\n/**/\n 1961,\n/**/\n 1960,\n/**/\n 1959,\n/**/\n 1958,\n/**/\n 1957,\n/**/\n 1956,\n/**/\n 1955,\n/**/\n 1954,\n/**/\n 1953,\n/**/\n 1952,\n/**/\n 1951,\n/**/\n 1950,\n/**/\n 1949,\n/**/\n 1948,\n/**/\n 1947,\n/**/\n 1946,\n/**/\n 1945,\n/**/\n 1944,\n/**/\n 1943,\n/**/\n 1942,\n/**/\n 1941,\n/**/\n 1940,\n/**/\n 1939,\n/**/\n 1938,\n/**/\n 1937,\n/**/\n 1936,\n/**/\n 1935,\n/**/\n 1934,\n/**/\n 1933,\n/**/\n 1932,\n/**/\n 1931,\n/**/\n 1930,\n/**/\n 1929,\n/**/\n 1928,\n/**/\n 1927,\n/**/\n 1926,\n/**/\n 1925,\n/**/\n 1924,\n/**/\n 1923,\n/**/\n 1922,\n/**/\n 1921,\n/**/\n 1920,\n/**/\n 1919,\n/**/\n 1918,\n/**/\n 1917,\n/**/\n 1916,\n/**/\n 1915,\n/**/\n 1914,\n/**/\n 1913,\n/**/\n 1912,\n/**/\n 1911,\n/**/\n 1910,\n/**/\n 1909,\n/**/\n 1908,\n/**/\n 1907,\n/**/\n 1906,\n/**/\n 1905,\n/**/\n 1904,\n/**/\n 1903,\n/**/\n 1902,\n/**/\n 1901,\n/**/\n 1900,\n/**/\n 1899,\n/**/\n 1898,\n/**/\n 1897,\n/**/\n 1896,\n/**/\n 1895,\n/**/\n 1894,\n/**/\n 1893,\n/**/\n 1892,\n/**/\n 1891,\n/**/\n 1890,\n/**/\n 1889,\n/**/\n 1888,\n/**/\n 1887,\n/**/\n 1886,\n/**/\n 1885,\n/**/\n 1884,\n/**/\n 1883,\n/**/\n 1882,\n/**/\n 1881,\n/**/\n 1880,\n/**/\n 1879,\n/**/\n 1878,\n/**/\n 1877,\n/**/\n 1876,\n/**/\n 1875,\n/**/\n 1874,\n/**/\n 1873,\n/**/\n 1872,\n/**/\n 1871,\n/**/\n 1870,\n/**/\n 1869,\n/**/\n 1868,\n/**/\n 1867,\n/**/\n 1866,\n/**/\n 1865,\n/**/\n 1864,\n/**/\n 1863,\n/**/\n 1862,\n/**/\n 1861,\n/**/\n 1860,\n/**/\n 1859,\n/**/\n 1858,\n/**/\n 1857,\n/**/\n 1856,\n/**/\n 1855,\n/**/\n 1854,\n/**/\n 1853,\n/**/\n 1852,\n/**/\n 1851,\n/**/\n 1850,\n/**/\n 1849,\n/**/\n 1848,\n/**/\n 1847,\n/**/\n 1846,\n/**/\n 1845,\n/**/\n 1844,\n/**/\n 1843,\n/**/\n 1842,\n/**/\n 1841,\n/**/\n 1840,\n/**/\n 1839,\n/**/\n 1838,\n/**/\n 1837,\n/**/\n 1836,\n/**/\n 1835,\n/**/\n 1834,\n/**/\n 1833,\n/**/\n 1832,\n/**/\n 1831,\n/**/\n 1830,\n/**/\n 1829,\n/**/\n 1828,\n/**/\n 1827,\n/**/\n 1826,\n/**/\n 1825,\n/**/\n 1824,\n/**/\n 1823,\n/**/\n 1822,\n/**/\n 1821,\n/**/\n 1820,\n/**/\n 1819,\n/**/\n 1818,\n/**/\n 1817,\n/**/\n 1816,\n/**/\n 1815,\n/**/\n 1814,\n/**/\n 1813,\n/**/\n 1812,\n/**/\n 1811,\n/**/\n 1810,\n/**/\n 1809,\n/**/\n 1808,\n/**/\n 1807,\n/**/\n 1806,\n/**/\n 1805,\n/**/\n 1804,\n/**/\n 1803,\n/**/\n 1802,\n/**/\n 1801,\n/**/\n 1800,\n/**/\n 1799,\n/**/\n 1798,\n/**/\n 1797,\n/**/\n 1796,\n/**/\n 1795,\n/**/\n 1794,\n/**/\n 1793,\n/**/\n 1792,\n/**/\n 1791,\n/**/\n 1790,\n/**/\n 1789,\n/**/\n 1788,\n/**/\n 1787,\n/**/\n 1786,\n/**/\n 1785,\n/**/\n 1784,\n/**/\n 1783,\n/**/\n 1782,\n/**/\n 1781,\n/**/\n 1780,\n/**/\n 1779,\n/**/\n 1778,\n/**/\n 1777,\n/**/\n 1776,\n/**/\n 1775,\n/**/\n 1774,\n/**/\n 1773,\n/**/\n 1772,\n/**/\n 1771,\n/**/\n 1770,\n/**/\n 1769,\n/**/\n 1768,\n/**/\n 1767,\n/**/\n 1766,\n/**/\n 1765,\n/**/\n 1764,\n/**/\n 1763,\n/**/\n 1762,\n/**/\n 1761,\n/**/\n 1760,\n/**/\n 1759,\n/**/\n 1758,\n/**/\n 1757,\n/**/\n 1756,\n/**/\n 1755,\n/**/\n 1754,\n/**/\n 1753,\n/**/\n 1752,\n/**/\n 1751,\n/**/\n 1750,\n/**/\n 1749,\n/**/\n 1748,\n/**/\n 1747,\n/**/\n 1746,\n/**/\n 1745,\n/**/\n 1744,\n/**/\n 1743,\n/**/\n 1742,\n/**/\n 1741,\n/**/\n 1740,\n/**/\n 1739,\n/**/\n 1738,\n/**/\n 1737,\n/**/\n 1736,\n/**/\n 1735,\n/**/\n 1734,\n/**/\n 1733,\n/**/\n 1732,\n/**/\n 1731,\n/**/\n 1730,\n/**/\n 1729,\n/**/\n 1728,\n/**/\n 1727,\n/**/\n 1726,\n/**/\n 1725,\n/**/\n 1724,\n/**/\n 1723,\n/**/\n 1722,\n/**/\n 1721,\n/**/\n 1720,\n/**/\n 1719,\n/**/\n 1718,\n/**/\n 1717,\n/**/\n 1716,\n/**/\n 1715,\n/**/\n 1714,\n/**/\n 1713,\n/**/\n 1712,\n/**/\n 1711,\n/**/\n 1710,\n/**/\n 1709,\n/**/\n 1708,\n/**/\n 1707,\n/**/\n 1706,\n/**/\n 1705,\n/**/\n 1704,\n/**/\n 1703,\n/**/\n 1702,\n/**/\n 1701,\n/**/\n 1700,\n/**/\n 1699,\n/**/\n 1698,\n/**/\n 1697,\n/**/\n 1696,\n/**/\n 1695,\n/**/\n 1694,\n/**/\n 1693,\n/**/\n 1692,\n/**/\n 1691,\n/**/\n 1690,\n/**/\n 1689,\n/**/\n 1688,\n/**/\n 1687,\n/**/\n 1686,\n/**/\n 1685,\n/**/\n 1684,\n/**/\n 1683,\n/**/\n 1682,\n/**/\n 1681,\n/**/\n 1680,\n/**/\n 1679,\n/**/\n 1678,\n/**/\n 1677,\n/**/\n 1676,\n/**/\n 1675,\n/**/\n 1674,\n/**/\n 1673,\n/**/\n 1672,\n/**/\n 1671,\n/**/\n 1670,\n/**/\n 1669,\n/**/\n 1668,\n/**/\n 1667,\n/**/\n 1666,\n/**/\n 1665,\n/**/\n 1664,\n/**/\n 1663,\n/**/\n 1662,\n/**/\n 1661,\n/**/\n 1660,\n/**/\n 1659,\n/**/\n 1658,\n/**/\n 1657,\n/**/\n 1656,\n/**/\n 1655,\n/**/\n 1654,\n/**/\n 1653,\n/**/\n 1652,\n/**/\n 1651,\n/**/\n 1650,\n/**/\n 1649,\n/**/\n 1648,\n/**/\n 1647,\n/**/\n 1646,\n/**/\n 1645,\n/**/\n 1644,\n/**/\n 1643,\n/**/\n 1642,\n/**/\n 1641,\n/**/\n 1640,\n/**/\n 1639,\n/**/\n 1638,\n/**/\n 1637,\n/**/\n 1636,\n/**/\n 1635,\n/**/\n 1634,\n/**/\n 1633,\n/**/\n 1632,\n/**/\n 1631,\n/**/\n 1630,\n/**/\n 1629,\n/**/\n 1628,\n/**/\n 1627,\n/**/\n 1626,\n/**/\n 1625,\n/**/\n 1624,\n/**/\n 1623,\n/**/\n 1622,\n/**/\n 1621,\n/**/\n 1620,\n/**/\n 1619,\n/**/\n 1618,\n/**/\n 1617,\n/**/\n 1616,\n/**/\n 1615,\n/**/\n 1614,\n/**/\n 1613,\n/**/\n 1612,\n/**/\n 1611,\n/**/\n 1610,\n/**/\n 1609,\n/**/\n 1608,\n/**/\n 1607,\n/**/\n 1606,\n/**/\n 1605,\n/**/\n 1604,\n/**/\n 1603,\n/**/\n 1602,\n/**/\n 1601,\n/**/\n 1600,\n/**/\n 1599,\n/**/\n 1598,\n/**/\n 1597,\n/**/\n 1596,\n/**/\n 1595,\n/**/\n 1594,\n/**/\n 1593,\n/**/\n 1592,\n/**/\n 1591,\n/**/\n 1590,\n/**/\n 1589,\n/**/\n 1588,\n/**/\n 1587,\n/**/\n 1586,\n/**/\n 1585,\n/**/\n 1584,\n/**/\n 1583,\n/**/\n 1582,\n/**/\n 1581,\n/**/\n 1580,\n/**/\n 1579,\n/**/\n 1578,\n/**/\n 1577,\n/**/\n 1576,\n/**/\n 1575,\n/**/\n 1574,\n/**/\n 1573,\n/**/\n 1572,\n/**/\n 1571,\n/**/\n 1570,\n/**/\n 1569,\n/**/\n 1568,\n/**/\n 1567,\n/**/\n 1566,\n/**/\n 1565,\n/**/\n 1564,\n/**/\n 1563,\n/**/\n 1562,\n/**/\n 1561,\n/**/\n 1560,\n/**/\n 1559,\n/**/\n 1558,\n/**/\n 1557,\n/**/\n 1556,\n/**/\n 1555,\n/**/\n 1554,\n/**/\n 1553,\n/**/\n 1552,\n/**/\n 1551,\n/**/\n 1550,\n/**/\n 1549,\n/**/\n 1548,\n/**/\n 1547,\n/**/\n 1546,\n/**/\n 1545,\n/**/\n 1544,\n/**/\n 1543,\n/**/\n 1542,\n/**/\n 1541,\n/**/\n 1540,\n/**/\n 1539,\n/**/\n 1538,\n/**/\n 1537,\n/**/\n 1536,\n/**/\n 1535,\n/**/\n 1534,\n/**/\n 1533,\n/**/\n 1532,\n/**/\n 1531,\n/**/\n 1530,\n/**/\n 1529,\n/**/\n 1528,\n/**/\n 1527,\n/**/\n 1526,\n/**/\n 1525,\n/**/\n 1524,\n/**/\n 1523,\n/**/\n 1522,\n/**/\n 1521,\n/**/\n 1520,\n/**/\n 1519,\n/**/\n 1518,\n/**/\n 1517,\n/**/\n 1516,\n/**/\n 1515,\n/**/\n 1514,\n/**/\n 1513,\n/**/\n 1512,\n/**/\n 1511,\n/**/\n 1510,\n/**/\n 1509,\n/**/\n 1508,\n/**/\n 1507,\n/**/\n 1506,\n/**/\n 1505,\n/**/\n 1504,\n/**/\n 1503,\n/**/\n 1502,\n/**/\n 1501,\n/**/\n 1500,\n/**/\n 1499,\n/**/\n 1498,\n/**/\n 1497,\n/**/\n 1496,\n/**/\n 1495,\n/**/\n 1494,\n/**/\n 1493,\n/**/\n 1492,\n/**/\n 1491,\n/**/\n 1490,\n/**/\n 1489,\n/**/\n 1488,\n/**/\n 1487,\n/**/\n 1486,\n/**/\n 1485,\n/**/\n 1484,\n/**/\n 1483,\n/**/\n 1482,\n/**/\n 1481,\n/**/\n 1480,\n/**/\n 1479,\n/**/\n 1478,\n/**/\n 1477,\n/**/\n 1476,\n/**/\n 1475,\n/**/\n 1474,\n/**/\n 1473,\n/**/\n 1472,\n/**/\n 1471,\n/**/\n 1470,\n/**/\n 1469,\n/**/\n 1468,\n/**/\n 1467,\n/**/\n 1466,\n/**/\n 1465,\n/**/\n 1464,\n/**/\n 1463,\n/**/\n 1462,\n/**/\n 1461,\n/**/\n 1460,\n/**/\n 1459,\n/**/\n 1458,\n/**/\n 1457,\n/**/\n 1456,\n/**/\n 1455,\n/**/\n 1454,\n/**/\n 1453,\n/**/\n 1452,\n/**/\n 1451,\n/**/\n 1450,\n/**/\n 1449,\n/**/\n 1448,\n/**/\n 1447,\n/**/\n 1446,\n/**/\n 1445,\n/**/\n 1444,\n/**/\n 1443,\n/**/\n 1442,\n/**/\n 1441,\n/**/\n 1440,\n/**/\n 1439,\n/**/\n 1438,\n/**/\n 1437,\n/**/\n 1436,\n/**/\n 1435,\n/**/\n 1434,\n/**/\n 1433,\n/**/\n 1432,\n/**/\n 1431,\n/**/\n 1430,\n/**/\n 1429,\n/**/\n 1428,\n/**/\n 1427,\n/**/\n 1426,\n/**/\n 1425,\n/**/\n 1424,\n/**/\n 1423,\n/**/\n 1422,\n/**/\n 1421,\n/**/\n 1420,\n/**/\n 1419,\n/**/\n 1418,\n/**/\n 1417,\n/**/\n 1416,\n/**/\n 1415,\n/**/\n 1414,\n/**/\n 1413,\n/**/\n 1412,\n/**/\n 1411,\n/**/\n 1410,\n/**/\n 1409,\n/**/\n 1408,\n/**/\n 1407,\n/**/\n 1406,\n/**/\n 1405,\n/**/\n 1404,\n/**/\n 1403,\n/**/\n 1402,\n/**/\n 1401,\n/**/\n 1400,\n/**/\n 1399,\n/**/\n 1398,\n/**/\n 1397,\n/**/\n 1396,\n/**/\n 1395,\n/**/\n 1394,\n/**/\n 1393,\n/**/\n 1392,\n/**/\n 1391,\n/**/\n 1390,\n/**/\n 1389,\n/**/\n 1388,\n/**/\n 1387,\n/**/\n 1386,\n/**/\n 1385,\n/**/\n 1384,\n/**/\n 1383,\n/**/\n 1382,\n/**/\n 1381,\n/**/\n 1380,\n/**/\n 1379,\n/**/\n 1378,\n/**/\n 1377,\n/**/\n 1376,\n/**/\n 1375,\n/**/\n 1374,\n/**/\n 1373,\n/**/\n 1372,\n/**/\n 1371,\n/**/\n 1370,\n/**/\n 1369,\n/**/\n 1368,\n/**/\n 1367,\n/**/\n 1366,\n/**/\n 1365,\n/**/\n 1364,\n/**/\n 1363,\n/**/\n 1362,\n/**/\n 1361,\n/**/\n 1360,\n/**/\n 1359,\n/**/\n 1358,\n/**/\n 1357,\n/**/\n 1356,\n/**/\n 1355,\n/**/\n 1354,\n/**/\n 1353,\n/**/\n 1352,\n/**/\n 1351,\n/**/\n 1350,\n/**/\n 1349,\n/**/\n 1348,\n/**/\n 1347,\n/**/\n 1346,\n/**/\n 1345,\n/**/\n 1344,\n/**/\n 1343,\n/**/\n 1342,\n/**/\n 1341,\n/**/\n 1340,\n/**/\n 1339,\n/**/\n 1338,\n/**/\n 1337,\n/**/\n 1336,\n/**/\n 1335,\n/**/\n 1334,\n/**/\n 1333,\n/**/\n 1332,\n/**/\n 1331,\n/**/\n 1330,\n/**/\n 1329,\n/**/\n 1328,\n/**/\n 1327,\n/**/\n 1326,\n/**/\n 1325,\n/**/\n 1324,\n/**/\n 1323,\n/**/\n 1322,\n/**/\n 1321,\n/**/\n 1320,\n/**/\n 1319,\n/**/\n 1318,\n/**/\n 1317,\n/**/\n 1316,\n/**/\n 1315,\n/**/\n 1314,\n/**/\n 1313,\n/**/\n 1312,\n/**/\n 1311,\n/**/\n 1310,\n/**/\n 1309,\n/**/\n 1308,\n/**/\n 1307,\n/**/\n 1306,\n/**/\n 1305,\n/**/\n 1304,\n/**/\n 1303,\n/**/\n 1302,\n/**/\n 1301,\n/**/\n 1300,\n/**/\n 1299,\n/**/\n 1298,\n/**/\n 1297,\n/**/\n 1296,\n/**/\n 1295,\n/**/\n 1294,\n/**/\n 1293,\n/**/\n 1292,\n/**/\n 1291,\n/**/\n 1290,\n/**/\n 1289,\n/**/\n 1288,\n/**/\n 1287,\n/**/\n 1286,\n/**/\n 1285,\n/**/\n 1284,\n/**/\n 1283,\n/**/\n 1282,\n/**/\n 1281,\n/**/\n 1280,\n/**/\n 1279,\n/**/\n 1278,\n/**/\n 1277,\n/**/\n 1276,\n/**/\n 1275,\n/**/\n 1274,\n/**/\n 1273,\n/**/\n 1272,\n/**/\n 1271,\n/**/\n 1270,\n/**/\n 1269,\n/**/\n 1268,\n/**/\n 1267,\n/**/\n 1266,\n/**/\n 1265,\n/**/\n 1264,\n/**/\n 1263,\n/**/\n 1262,\n/**/\n 1261,\n/**/\n 1260,\n/**/\n 1259,\n/**/\n 1258,\n/**/\n 1257,\n/**/\n 1256,\n/**/\n 1255,\n/**/\n 1254,\n/**/\n 1253,\n/**/\n 1252,\n/**/\n 1251,\n/**/\n 1250,\n/**/\n 1249,\n/**/\n 1248,\n/**/\n 1247,\n/**/\n 1246,\n/**/\n 1245,\n/**/\n 1244,\n/**/\n 1243,\n/**/\n 1242,\n/**/\n 1241,\n/**/\n 1240,\n/**/\n 1239,\n/**/\n 1238,\n/**/\n 1237,\n/**/\n 1236,\n/**/\n 1235,\n/**/\n 1234,\n/**/\n 1233,\n/**/\n 1232,\n/**/\n 1231,\n/**/\n 1230,\n/**/\n 1229,\n/**/\n 1228,\n/**/\n 1227,\n/**/\n 1226,\n/**/\n 1225,\n/**/\n 1224,\n/**/\n 1223,\n/**/\n 1222,\n/**/\n 1221,\n/**/\n 1220,\n/**/\n 1219,\n/**/\n 1218,\n/**/\n 1217,\n/**/\n 1216,\n/**/\n 1215,\n/**/\n 1214,\n/**/\n 1213,\n/**/\n 1212,\n/**/\n 1211,\n/**/\n 1210,\n/**/\n 1209,\n/**/\n 1208,\n/**/\n 1207,\n/**/\n 1206,\n/**/\n 1205,\n/**/\n 1204,\n/**/\n 1203,\n/**/\n 1202,\n/**/\n 1201,\n/**/\n 1200,\n/**/\n 1199,\n/**/\n 1198,\n/**/\n 1197,\n/**/\n 1196,\n/**/\n 1195,\n/**/\n 1194,\n/**/\n 1193,\n/**/\n 1192,\n/**/\n 1191,\n/**/\n 1190,\n/**/\n 1189,\n/**/\n 1188,\n/**/\n 1187,\n/**/\n 1186,\n/**/\n 1185,\n/**/\n 1184,\n/**/\n 1183,\n/**/\n 1182,\n/**/\n 1181,\n/**/\n 1180,\n/**/\n 1179,\n/**/\n 1178,\n/**/\n 1177,\n/**/\n 1176,\n/**/\n 1175,\n/**/\n 1174,\n/**/\n 1173,\n/**/\n 1172,\n/**/\n 1171,\n/**/\n 1170,\n/**/\n 1169,\n/**/\n 1168,\n/**/\n 1167,\n/**/\n 1166,\n/**/\n 1165,\n/**/\n 1164,\n/**/\n 1163,\n/**/\n 1162,\n/**/\n 1161,\n/**/\n 1160,\n/**/\n 1159,\n/**/\n 1158,\n/**/\n 1157,\n/**/\n 1156,\n/**/\n 1155,\n/**/\n 1154,\n/**/\n 1153,\n/**/\n 1152,\n/**/\n 1151,\n/**/\n 1150,\n/**/\n 1149,\n/**/\n 1148,\n/**/\n 1147,\n/**/\n 1146,\n/**/\n 1145,\n/**/\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 while (l < h)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\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 version8<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": [2081, 87, 736], "buggy_code_start_loc": [2079, 1, 736], "filenames": ["src/indent.c", "src/testdir/test_lispwords.vim", "src/version.c"], "fixing_code_end_loc": [2084, 98, 739], "fixing_code_start_loc": [2079, 1, 737], "message": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "C88D3533-C1C8-4615-A2D5-30AC85BA943B", "versionEndExcluding": "8.2.5151", "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}, {"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": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Una Lectura Fuera de L\u00edmites en el repositorio de GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2183", "lastModified": "2023-05-03T12:15:46.177", "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-06-23T19:15:08.577", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d74ca3f9-380d-4c0a-b61c-11113cc98975"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GFD2A4YLBR7OIRHTL7CK6YNMEIQ264CN/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U743FMJGFQ35GBPCQ6OWMVZEJPDFVEWM/"}, {"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-125"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, "type": "CWE-125"}
| 319
|
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 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 5151,",
"/**/\n 5150,\n/**/\n 5149,\n/**/\n 5148,\n/**/\n 5147,\n/**/\n 5146,\n/**/\n 5145,\n/**/\n 5144,\n/**/\n 5143,\n/**/\n 5142,\n/**/\n 5141,\n/**/\n 5140,\n/**/\n 5139,\n/**/\n 5138,\n/**/\n 5137,\n/**/\n 5136,\n/**/\n 5135,\n/**/\n 5134,\n/**/\n 5133,\n/**/\n 5132,\n/**/\n 5131,\n/**/\n 5130,\n/**/\n 5129,\n/**/\n 5128,\n/**/\n 5127,\n/**/\n 5126,\n/**/\n 5125,\n/**/\n 5124,\n/**/\n 5123,\n/**/\n 5122,\n/**/\n 5121,\n/**/\n 5120,\n/**/\n 5119,\n/**/\n 5118,\n/**/\n 5117,\n/**/\n 5116,\n/**/\n 5115,\n/**/\n 5114,\n/**/\n 5113,\n/**/\n 5112,\n/**/\n 5111,\n/**/\n 5110,\n/**/\n 5109,\n/**/\n 5108,\n/**/\n 5107,\n/**/\n 5106,\n/**/\n 5105,\n/**/\n 5104,\n/**/\n 5103,\n/**/\n 5102,\n/**/\n 5101,\n/**/\n 5100,\n/**/\n 5099,\n/**/\n 5098,\n/**/\n 5097,\n/**/\n 5096,\n/**/\n 5095,\n/**/\n 5094,\n/**/\n 5093,\n/**/\n 5092,\n/**/\n 5091,\n/**/\n 5090,\n/**/\n 5089,\n/**/\n 5088,\n/**/\n 5087,\n/**/\n 5086,\n/**/\n 5085,\n/**/\n 5084,\n/**/\n 5083,\n/**/\n 5082,\n/**/\n 5081,\n/**/\n 5080,\n/**/\n 5079,\n/**/\n 5078,\n/**/\n 5077,\n/**/\n 5076,\n/**/\n 5075,\n/**/\n 5074,\n/**/\n 5073,\n/**/\n 5072,\n/**/\n 5071,\n/**/\n 5070,\n/**/\n 5069,\n/**/\n 5068,\n/**/\n 5067,\n/**/\n 5066,\n/**/\n 5065,\n/**/\n 5064,\n/**/\n 5063,\n/**/\n 5062,\n/**/\n 5061,\n/**/\n 5060,\n/**/\n 5059,\n/**/\n 5058,\n/**/\n 5057,\n/**/\n 5056,\n/**/\n 5055,\n/**/\n 5054,\n/**/\n 5053,\n/**/\n 5052,\n/**/\n 5051,\n/**/\n 5050,\n/**/\n 5049,\n/**/\n 5048,\n/**/\n 5047,\n/**/\n 5046,\n/**/\n 5045,\n/**/\n 5044,\n/**/\n 5043,\n/**/\n 5042,\n/**/\n 5041,\n/**/\n 5040,\n/**/\n 5039,\n/**/\n 5038,\n/**/\n 5037,\n/**/\n 5036,\n/**/\n 5035,\n/**/\n 5034,\n/**/\n 5033,\n/**/\n 5032,\n/**/\n 5031,\n/**/\n 5030,\n/**/\n 5029,\n/**/\n 5028,\n/**/\n 5027,\n/**/\n 5026,\n/**/\n 5025,\n/**/\n 5024,\n/**/\n 5023,\n/**/\n 5022,\n/**/\n 5021,\n/**/\n 5020,\n/**/\n 5019,\n/**/\n 5018,\n/**/\n 5017,\n/**/\n 5016,\n/**/\n 5015,\n/**/\n 5014,\n/**/\n 5013,\n/**/\n 5012,\n/**/\n 5011,\n/**/\n 5010,\n/**/\n 5009,\n/**/\n 5008,\n/**/\n 5007,\n/**/\n 5006,\n/**/\n 5005,\n/**/\n 5004,\n/**/\n 5003,\n/**/\n 5002,\n/**/\n 5001,\n/**/\n 5000,\n/**/\n 4999,\n/**/\n 4998,\n/**/\n 4997,\n/**/\n 4996,\n/**/\n 4995,\n/**/\n 4994,\n/**/\n 4993,\n/**/\n 4992,\n/**/\n 4991,\n/**/\n 4990,\n/**/\n 4989,\n/**/\n 4988,\n/**/\n 4987,\n/**/\n 4986,\n/**/\n 4985,\n/**/\n 4984,\n/**/\n 4983,\n/**/\n 4982,\n/**/\n 4981,\n/**/\n 4980,\n/**/\n 4979,\n/**/\n 4978,\n/**/\n 4977,\n/**/\n 4976,\n/**/\n 4975,\n/**/\n 4974,\n/**/\n 4973,\n/**/\n 4972,\n/**/\n 4971,\n/**/\n 4970,\n/**/\n 4969,\n/**/\n 4968,\n/**/\n 4967,\n/**/\n 4966,\n/**/\n 4965,\n/**/\n 4964,\n/**/\n 4963,\n/**/\n 4962,\n/**/\n 4961,\n/**/\n 4960,\n/**/\n 4959,\n/**/\n 4958,\n/**/\n 4957,\n/**/\n 4956,\n/**/\n 4955,\n/**/\n 4954,\n/**/\n 4953,\n/**/\n 4952,\n/**/\n 4951,\n/**/\n 4950,\n/**/\n 4949,\n/**/\n 4948,\n/**/\n 4947,\n/**/\n 4946,\n/**/\n 4945,\n/**/\n 4944,\n/**/\n 4943,\n/**/\n 4942,\n/**/\n 4941,\n/**/\n 4940,\n/**/\n 4939,\n/**/\n 4938,\n/**/\n 4937,\n/**/\n 4936,\n/**/\n 4935,\n/**/\n 4934,\n/**/\n 4933,\n/**/\n 4932,\n/**/\n 4931,\n/**/\n 4930,\n/**/\n 4929,\n/**/\n 4928,\n/**/\n 4927,\n/**/\n 4926,\n/**/\n 4925,\n/**/\n 4924,\n/**/\n 4923,\n/**/\n 4922,\n/**/\n 4921,\n/**/\n 4920,\n/**/\n 4919,\n/**/\n 4918,\n/**/\n 4917,\n/**/\n 4916,\n/**/\n 4915,\n/**/\n 4914,\n/**/\n 4913,\n/**/\n 4912,\n/**/\n 4911,\n/**/\n 4910,\n/**/\n 4909,\n/**/\n 4908,\n/**/\n 4907,\n/**/\n 4906,\n/**/\n 4905,\n/**/\n 4904,\n/**/\n 4903,\n/**/\n 4902,\n/**/\n 4901,\n/**/\n 4900,\n/**/\n 4899,\n/**/\n 4898,\n/**/\n 4897,\n/**/\n 4896,\n/**/\n 4895,\n/**/\n 4894,\n/**/\n 4893,\n/**/\n 4892,\n/**/\n 4891,\n/**/\n 4890,\n/**/\n 4889,\n/**/\n 4888,\n/**/\n 4887,\n/**/\n 4886,\n/**/\n 4885,\n/**/\n 4884,\n/**/\n 4883,\n/**/\n 4882,\n/**/\n 4881,\n/**/\n 4880,\n/**/\n 4879,\n/**/\n 4878,\n/**/\n 4877,\n/**/\n 4876,\n/**/\n 4875,\n/**/\n 4874,\n/**/\n 4873,\n/**/\n 4872,\n/**/\n 4871,\n/**/\n 4870,\n/**/\n 4869,\n/**/\n 4868,\n/**/\n 4867,\n/**/\n 4866,\n/**/\n 4865,\n/**/\n 4864,\n/**/\n 4863,\n/**/\n 4862,\n/**/\n 4861,\n/**/\n 4860,\n/**/\n 4859,\n/**/\n 4858,\n/**/\n 4857,\n/**/\n 4856,\n/**/\n 4855,\n/**/\n 4854,\n/**/\n 4853,\n/**/\n 4852,\n/**/\n 4851,\n/**/\n 4850,\n/**/\n 4849,\n/**/\n 4848,\n/**/\n 4847,\n/**/\n 4846,\n/**/\n 4845,\n/**/\n 4844,\n/**/\n 4843,\n/**/\n 4842,\n/**/\n 4841,\n/**/\n 4840,\n/**/\n 4839,\n/**/\n 4838,\n/**/\n 4837,\n/**/\n 4836,\n/**/\n 4835,\n/**/\n 4834,\n/**/\n 4833,\n/**/\n 4832,\n/**/\n 4831,\n/**/\n 4830,\n/**/\n 4829,\n/**/\n 4828,\n/**/\n 4827,\n/**/\n 4826,\n/**/\n 4825,\n/**/\n 4824,\n/**/\n 4823,\n/**/\n 4822,\n/**/\n 4821,\n/**/\n 4820,\n/**/\n 4819,\n/**/\n 4818,\n/**/\n 4817,\n/**/\n 4816,\n/**/\n 4815,\n/**/\n 4814,\n/**/\n 4813,\n/**/\n 4812,\n/**/\n 4811,\n/**/\n 4810,\n/**/\n 4809,\n/**/\n 4808,\n/**/\n 4807,\n/**/\n 4806,\n/**/\n 4805,\n/**/\n 4804,\n/**/\n 4803,\n/**/\n 4802,\n/**/\n 4801,\n/**/\n 4800,\n/**/\n 4799,\n/**/\n 4798,\n/**/\n 4797,\n/**/\n 4796,\n/**/\n 4795,\n/**/\n 4794,\n/**/\n 4793,\n/**/\n 4792,\n/**/\n 4791,\n/**/\n 4790,\n/**/\n 4789,\n/**/\n 4788,\n/**/\n 4787,\n/**/\n 4786,\n/**/\n 4785,\n/**/\n 4784,\n/**/\n 4783,\n/**/\n 4782,\n/**/\n 4781,\n/**/\n 4780,\n/**/\n 4779,\n/**/\n 4778,\n/**/\n 4777,\n/**/\n 4776,\n/**/\n 4775,\n/**/\n 4774,\n/**/\n 4773,\n/**/\n 4772,\n/**/\n 4771,\n/**/\n 4770,\n/**/\n 4769,\n/**/\n 4768,\n/**/\n 4767,\n/**/\n 4766,\n/**/\n 4765,\n/**/\n 4764,\n/**/\n 4763,\n/**/\n 4762,\n/**/\n 4761,\n/**/\n 4760,\n/**/\n 4759,\n/**/\n 4758,\n/**/\n 4757,\n/**/\n 4756,\n/**/\n 4755,\n/**/\n 4754,\n/**/\n 4753,\n/**/\n 4752,\n/**/\n 4751,\n/**/\n 4750,\n/**/\n 4749,\n/**/\n 4748,\n/**/\n 4747,\n/**/\n 4746,\n/**/\n 4745,\n/**/\n 4744,\n/**/\n 4743,\n/**/\n 4742,\n/**/\n 4741,\n/**/\n 4740,\n/**/\n 4739,\n/**/\n 4738,\n/**/\n 4737,\n/**/\n 4736,\n/**/\n 4735,\n/**/\n 4734,\n/**/\n 4733,\n/**/\n 4732,\n/**/\n 4731,\n/**/\n 4730,\n/**/\n 4729,\n/**/\n 4728,\n/**/\n 4727,\n/**/\n 4726,\n/**/\n 4725,\n/**/\n 4724,\n/**/\n 4723,\n/**/\n 4722,\n/**/\n 4721,\n/**/\n 4720,\n/**/\n 4719,\n/**/\n 4718,\n/**/\n 4717,\n/**/\n 4716,\n/**/\n 4715,\n/**/\n 4714,\n/**/\n 4713,\n/**/\n 4712,\n/**/\n 4711,\n/**/\n 4710,\n/**/\n 4709,\n/**/\n 4708,\n/**/\n 4707,\n/**/\n 4706,\n/**/\n 4705,\n/**/\n 4704,\n/**/\n 4703,\n/**/\n 4702,\n/**/\n 4701,\n/**/\n 4700,\n/**/\n 4699,\n/**/\n 4698,\n/**/\n 4697,\n/**/\n 4696,\n/**/\n 4695,\n/**/\n 4694,\n/**/\n 4693,\n/**/\n 4692,\n/**/\n 4691,\n/**/\n 4690,\n/**/\n 4689,\n/**/\n 4688,\n/**/\n 4687,\n/**/\n 4686,\n/**/\n 4685,\n/**/\n 4684,\n/**/\n 4683,\n/**/\n 4682,\n/**/\n 4681,\n/**/\n 4680,\n/**/\n 4679,\n/**/\n 4678,\n/**/\n 4677,\n/**/\n 4676,\n/**/\n 4675,\n/**/\n 4674,\n/**/\n 4673,\n/**/\n 4672,\n/**/\n 4671,\n/**/\n 4670,\n/**/\n 4669,\n/**/\n 4668,\n/**/\n 4667,\n/**/\n 4666,\n/**/\n 4665,\n/**/\n 4664,\n/**/\n 4663,\n/**/\n 4662,\n/**/\n 4661,\n/**/\n 4660,\n/**/\n 4659,\n/**/\n 4658,\n/**/\n 4657,\n/**/\n 4656,\n/**/\n 4655,\n/**/\n 4654,\n/**/\n 4653,\n/**/\n 4652,\n/**/\n 4651,\n/**/\n 4650,\n/**/\n 4649,\n/**/\n 4648,\n/**/\n 4647,\n/**/\n 4646,\n/**/\n 4645,\n/**/\n 4644,\n/**/\n 4643,\n/**/\n 4642,\n/**/\n 4641,\n/**/\n 4640,\n/**/\n 4639,\n/**/\n 4638,\n/**/\n 4637,\n/**/\n 4636,\n/**/\n 4635,\n/**/\n 4634,\n/**/\n 4633,\n/**/\n 4632,\n/**/\n 4631,\n/**/\n 4630,\n/**/\n 4629,\n/**/\n 4628,\n/**/\n 4627,\n/**/\n 4626,\n/**/\n 4625,\n/**/\n 4624,\n/**/\n 4623,\n/**/\n 4622,\n/**/\n 4621,\n/**/\n 4620,\n/**/\n 4619,\n/**/\n 4618,\n/**/\n 4617,\n/**/\n 4616,\n/**/\n 4615,\n/**/\n 4614,\n/**/\n 4613,\n/**/\n 4612,\n/**/\n 4611,\n/**/\n 4610,\n/**/\n 4609,\n/**/\n 4608,\n/**/\n 4607,\n/**/\n 4606,\n/**/\n 4605,\n/**/\n 4604,\n/**/\n 4603,\n/**/\n 4602,\n/**/\n 4601,\n/**/\n 4600,\n/**/\n 4599,\n/**/\n 4598,\n/**/\n 4597,\n/**/\n 4596,\n/**/\n 4595,\n/**/\n 4594,\n/**/\n 4593,\n/**/\n 4592,\n/**/\n 4591,\n/**/\n 4590,\n/**/\n 4589,\n/**/\n 4588,\n/**/\n 4587,\n/**/\n 4586,\n/**/\n 4585,\n/**/\n 4584,\n/**/\n 4583,\n/**/\n 4582,\n/**/\n 4581,\n/**/\n 4580,\n/**/\n 4579,\n/**/\n 4578,\n/**/\n 4577,\n/**/\n 4576,\n/**/\n 4575,\n/**/\n 4574,\n/**/\n 4573,\n/**/\n 4572,\n/**/\n 4571,\n/**/\n 4570,\n/**/\n 4569,\n/**/\n 4568,\n/**/\n 4567,\n/**/\n 4566,\n/**/\n 4565,\n/**/\n 4564,\n/**/\n 4563,\n/**/\n 4562,\n/**/\n 4561,\n/**/\n 4560,\n/**/\n 4559,\n/**/\n 4558,\n/**/\n 4557,\n/**/\n 4556,\n/**/\n 4555,\n/**/\n 4554,\n/**/\n 4553,\n/**/\n 4552,\n/**/\n 4551,\n/**/\n 4550,\n/**/\n 4549,\n/**/\n 4548,\n/**/\n 4547,\n/**/\n 4546,\n/**/\n 4545,\n/**/\n 4544,\n/**/\n 4543,\n/**/\n 4542,\n/**/\n 4541,\n/**/\n 4540,\n/**/\n 4539,\n/**/\n 4538,\n/**/\n 4537,\n/**/\n 4536,\n/**/\n 4535,\n/**/\n 4534,\n/**/\n 4533,\n/**/\n 4532,\n/**/\n 4531,\n/**/\n 4530,\n/**/\n 4529,\n/**/\n 4528,\n/**/\n 4527,\n/**/\n 4526,\n/**/\n 4525,\n/**/\n 4524,\n/**/\n 4523,\n/**/\n 4522,\n/**/\n 4521,\n/**/\n 4520,\n/**/\n 4519,\n/**/\n 4518,\n/**/\n 4517,\n/**/\n 4516,\n/**/\n 4515,\n/**/\n 4514,\n/**/\n 4513,\n/**/\n 4512,\n/**/\n 4511,\n/**/\n 4510,\n/**/\n 4509,\n/**/\n 4508,\n/**/\n 4507,\n/**/\n 4506,\n/**/\n 4505,\n/**/\n 4504,\n/**/\n 4503,\n/**/\n 4502,\n/**/\n 4501,\n/**/\n 4500,\n/**/\n 4499,\n/**/\n 4498,\n/**/\n 4497,\n/**/\n 4496,\n/**/\n 4495,\n/**/\n 4494,\n/**/\n 4493,\n/**/\n 4492,\n/**/\n 4491,\n/**/\n 4490,\n/**/\n 4489,\n/**/\n 4488,\n/**/\n 4487,\n/**/\n 4486,\n/**/\n 4485,\n/**/\n 4484,\n/**/\n 4483,\n/**/\n 4482,\n/**/\n 4481,\n/**/\n 4480,\n/**/\n 4479,\n/**/\n 4478,\n/**/\n 4477,\n/**/\n 4476,\n/**/\n 4475,\n/**/\n 4474,\n/**/\n 4473,\n/**/\n 4472,\n/**/\n 4471,\n/**/\n 4470,\n/**/\n 4469,\n/**/\n 4468,\n/**/\n 4467,\n/**/\n 4466,\n/**/\n 4465,\n/**/\n 4464,\n/**/\n 4463,\n/**/\n 4462,\n/**/\n 4461,\n/**/\n 4460,\n/**/\n 4459,\n/**/\n 4458,\n/**/\n 4457,\n/**/\n 4456,\n/**/\n 4455,\n/**/\n 4454,\n/**/\n 4453,\n/**/\n 4452,\n/**/\n 4451,\n/**/\n 4450,\n/**/\n 4449,\n/**/\n 4448,\n/**/\n 4447,\n/**/\n 4446,\n/**/\n 4445,\n/**/\n 4444,\n/**/\n 4443,\n/**/\n 4442,\n/**/\n 4441,\n/**/\n 4440,\n/**/\n 4439,\n/**/\n 4438,\n/**/\n 4437,\n/**/\n 4436,\n/**/\n 4435,\n/**/\n 4434,\n/**/\n 4433,\n/**/\n 4432,\n/**/\n 4431,\n/**/\n 4430,\n/**/\n 4429,\n/**/\n 4428,\n/**/\n 4427,\n/**/\n 4426,\n/**/\n 4425,\n/**/\n 4424,\n/**/\n 4423,\n/**/\n 4422,\n/**/\n 4421,\n/**/\n 4420,\n/**/\n 4419,\n/**/\n 4418,\n/**/\n 4417,\n/**/\n 4416,\n/**/\n 4415,\n/**/\n 4414,\n/**/\n 4413,\n/**/\n 4412,\n/**/\n 4411,\n/**/\n 4410,\n/**/\n 4409,\n/**/\n 4408,\n/**/\n 4407,\n/**/\n 4406,\n/**/\n 4405,\n/**/\n 4404,\n/**/\n 4403,\n/**/\n 4402,\n/**/\n 4401,\n/**/\n 4400,\n/**/\n 4399,\n/**/\n 4398,\n/**/\n 4397,\n/**/\n 4396,\n/**/\n 4395,\n/**/\n 4394,\n/**/\n 4393,\n/**/\n 4392,\n/**/\n 4391,\n/**/\n 4390,\n/**/\n 4389,\n/**/\n 4388,\n/**/\n 4387,\n/**/\n 4386,\n/**/\n 4385,\n/**/\n 4384,\n/**/\n 4383,\n/**/\n 4382,\n/**/\n 4381,\n/**/\n 4380,\n/**/\n 4379,\n/**/\n 4378,\n/**/\n 4377,\n/**/\n 4376,\n/**/\n 4375,\n/**/\n 4374,\n/**/\n 4373,\n/**/\n 4372,\n/**/\n 4371,\n/**/\n 4370,\n/**/\n 4369,\n/**/\n 4368,\n/**/\n 4367,\n/**/\n 4366,\n/**/\n 4365,\n/**/\n 4364,\n/**/\n 4363,\n/**/\n 4362,\n/**/\n 4361,\n/**/\n 4360,\n/**/\n 4359,\n/**/\n 4358,\n/**/\n 4357,\n/**/\n 4356,\n/**/\n 4355,\n/**/\n 4354,\n/**/\n 4353,\n/**/\n 4352,\n/**/\n 4351,\n/**/\n 4350,\n/**/\n 4349,\n/**/\n 4348,\n/**/\n 4347,\n/**/\n 4346,\n/**/\n 4345,\n/**/\n 4344,\n/**/\n 4343,\n/**/\n 4342,\n/**/\n 4341,\n/**/\n 4340,\n/**/\n 4339,\n/**/\n 4338,\n/**/\n 4337,\n/**/\n 4336,\n/**/\n 4335,\n/**/\n 4334,\n/**/\n 4333,\n/**/\n 4332,\n/**/\n 4331,\n/**/\n 4330,\n/**/\n 4329,\n/**/\n 4328,\n/**/\n 4327,\n/**/\n 4326,\n/**/\n 4325,\n/**/\n 4324,\n/**/\n 4323,\n/**/\n 4322,\n/**/\n 4321,\n/**/\n 4320,\n/**/\n 4319,\n/**/\n 4318,\n/**/\n 4317,\n/**/\n 4316,\n/**/\n 4315,\n/**/\n 4314,\n/**/\n 4313,\n/**/\n 4312,\n/**/\n 4311,\n/**/\n 4310,\n/**/\n 4309,\n/**/\n 4308,\n/**/\n 4307,\n/**/\n 4306,\n/**/\n 4305,\n/**/\n 4304,\n/**/\n 4303,\n/**/\n 4302,\n/**/\n 4301,\n/**/\n 4300,\n/**/\n 4299,\n/**/\n 4298,\n/**/\n 4297,\n/**/\n 4296,\n/**/\n 4295,\n/**/\n 4294,\n/**/\n 4293,\n/**/\n 4292,\n/**/\n 4291,\n/**/\n 4290,\n/**/\n 4289,\n/**/\n 4288,\n/**/\n 4287,\n/**/\n 4286,\n/**/\n 4285,\n/**/\n 4284,\n/**/\n 4283,\n/**/\n 4282,\n/**/\n 4281,\n/**/\n 4280,\n/**/\n 4279,\n/**/\n 4278,\n/**/\n 4277,\n/**/\n 4276,\n/**/\n 4275,\n/**/\n 4274,\n/**/\n 4273,\n/**/\n 4272,\n/**/\n 4271,\n/**/\n 4270,\n/**/\n 4269,\n/**/\n 4268,\n/**/\n 4267,\n/**/\n 4266,\n/**/\n 4265,\n/**/\n 4264,\n/**/\n 4263,\n/**/\n 4262,\n/**/\n 4261,\n/**/\n 4260,\n/**/\n 4259,\n/**/\n 4258,\n/**/\n 4257,\n/**/\n 4256,\n/**/\n 4255,\n/**/\n 4254,\n/**/\n 4253,\n/**/\n 4252,\n/**/\n 4251,\n/**/\n 4250,\n/**/\n 4249,\n/**/\n 4248,\n/**/\n 4247,\n/**/\n 4246,\n/**/\n 4245,\n/**/\n 4244,\n/**/\n 4243,\n/**/\n 4242,\n/**/\n 4241,\n/**/\n 4240,\n/**/\n 4239,\n/**/\n 4238,\n/**/\n 4237,\n/**/\n 4236,\n/**/\n 4235,\n/**/\n 4234,\n/**/\n 4233,\n/**/\n 4232,\n/**/\n 4231,\n/**/\n 4230,\n/**/\n 4229,\n/**/\n 4228,\n/**/\n 4227,\n/**/\n 4226,\n/**/\n 4225,\n/**/\n 4224,\n/**/\n 4223,\n/**/\n 4222,\n/**/\n 4221,\n/**/\n 4220,\n/**/\n 4219,\n/**/\n 4218,\n/**/\n 4217,\n/**/\n 4216,\n/**/\n 4215,\n/**/\n 4214,\n/**/\n 4213,\n/**/\n 4212,\n/**/\n 4211,\n/**/\n 4210,\n/**/\n 4209,\n/**/\n 4208,\n/**/\n 4207,\n/**/\n 4206,\n/**/\n 4205,\n/**/\n 4204,\n/**/\n 4203,\n/**/\n 4202,\n/**/\n 4201,\n/**/\n 4200,\n/**/\n 4199,\n/**/\n 4198,\n/**/\n 4197,\n/**/\n 4196,\n/**/\n 4195,\n/**/\n 4194,\n/**/\n 4193,\n/**/\n 4192,\n/**/\n 4191,\n/**/\n 4190,\n/**/\n 4189,\n/**/\n 4188,\n/**/\n 4187,\n/**/\n 4186,\n/**/\n 4185,\n/**/\n 4184,\n/**/\n 4183,\n/**/\n 4182,\n/**/\n 4181,\n/**/\n 4180,\n/**/\n 4179,\n/**/\n 4178,\n/**/\n 4177,\n/**/\n 4176,\n/**/\n 4175,\n/**/\n 4174,\n/**/\n 4173,\n/**/\n 4172,\n/**/\n 4171,\n/**/\n 4170,\n/**/\n 4169,\n/**/\n 4168,\n/**/\n 4167,\n/**/\n 4166,\n/**/\n 4165,\n/**/\n 4164,\n/**/\n 4163,\n/**/\n 4162,\n/**/\n 4161,\n/**/\n 4160,\n/**/\n 4159,\n/**/\n 4158,\n/**/\n 4157,\n/**/\n 4156,\n/**/\n 4155,\n/**/\n 4154,\n/**/\n 4153,\n/**/\n 4152,\n/**/\n 4151,\n/**/\n 4150,\n/**/\n 4149,\n/**/\n 4148,\n/**/\n 4147,\n/**/\n 4146,\n/**/\n 4145,\n/**/\n 4144,\n/**/\n 4143,\n/**/\n 4142,\n/**/\n 4141,\n/**/\n 4140,\n/**/\n 4139,\n/**/\n 4138,\n/**/\n 4137,\n/**/\n 4136,\n/**/\n 4135,\n/**/\n 4134,\n/**/\n 4133,\n/**/\n 4132,\n/**/\n 4131,\n/**/\n 4130,\n/**/\n 4129,\n/**/\n 4128,\n/**/\n 4127,\n/**/\n 4126,\n/**/\n 4125,\n/**/\n 4124,\n/**/\n 4123,\n/**/\n 4122,\n/**/\n 4121,\n/**/\n 4120,\n/**/\n 4119,\n/**/\n 4118,\n/**/\n 4117,\n/**/\n 4116,\n/**/\n 4115,\n/**/\n 4114,\n/**/\n 4113,\n/**/\n 4112,\n/**/\n 4111,\n/**/\n 4110,\n/**/\n 4109,\n/**/\n 4108,\n/**/\n 4107,\n/**/\n 4106,\n/**/\n 4105,\n/**/\n 4104,\n/**/\n 4103,\n/**/\n 4102,\n/**/\n 4101,\n/**/\n 4100,\n/**/\n 4099,\n/**/\n 4098,\n/**/\n 4097,\n/**/\n 4096,\n/**/\n 4095,\n/**/\n 4094,\n/**/\n 4093,\n/**/\n 4092,\n/**/\n 4091,\n/**/\n 4090,\n/**/\n 4089,\n/**/\n 4088,\n/**/\n 4087,\n/**/\n 4086,\n/**/\n 4085,\n/**/\n 4084,\n/**/\n 4083,\n/**/\n 4082,\n/**/\n 4081,\n/**/\n 4080,\n/**/\n 4079,\n/**/\n 4078,\n/**/\n 4077,\n/**/\n 4076,\n/**/\n 4075,\n/**/\n 4074,\n/**/\n 4073,\n/**/\n 4072,\n/**/\n 4071,\n/**/\n 4070,\n/**/\n 4069,\n/**/\n 4068,\n/**/\n 4067,\n/**/\n 4066,\n/**/\n 4065,\n/**/\n 4064,\n/**/\n 4063,\n/**/\n 4062,\n/**/\n 4061,\n/**/\n 4060,\n/**/\n 4059,\n/**/\n 4058,\n/**/\n 4057,\n/**/\n 4056,\n/**/\n 4055,\n/**/\n 4054,\n/**/\n 4053,\n/**/\n 4052,\n/**/\n 4051,\n/**/\n 4050,\n/**/\n 4049,\n/**/\n 4048,\n/**/\n 4047,\n/**/\n 4046,\n/**/\n 4045,\n/**/\n 4044,\n/**/\n 4043,\n/**/\n 4042,\n/**/\n 4041,\n/**/\n 4040,\n/**/\n 4039,\n/**/\n 4038,\n/**/\n 4037,\n/**/\n 4036,\n/**/\n 4035,\n/**/\n 4034,\n/**/\n 4033,\n/**/\n 4032,\n/**/\n 4031,\n/**/\n 4030,\n/**/\n 4029,\n/**/\n 4028,\n/**/\n 4027,\n/**/\n 4026,\n/**/\n 4025,\n/**/\n 4024,\n/**/\n 4023,\n/**/\n 4022,\n/**/\n 4021,\n/**/\n 4020,\n/**/\n 4019,\n/**/\n 4018,\n/**/\n 4017,\n/**/\n 4016,\n/**/\n 4015,\n/**/\n 4014,\n/**/\n 4013,\n/**/\n 4012,\n/**/\n 4011,\n/**/\n 4010,\n/**/\n 4009,\n/**/\n 4008,\n/**/\n 4007,\n/**/\n 4006,\n/**/\n 4005,\n/**/\n 4004,\n/**/\n 4003,\n/**/\n 4002,\n/**/\n 4001,\n/**/\n 4000,\n/**/\n 3999,\n/**/\n 3998,\n/**/\n 3997,\n/**/\n 3996,\n/**/\n 3995,\n/**/\n 3994,\n/**/\n 3993,\n/**/\n 3992,\n/**/\n 3991,\n/**/\n 3990,\n/**/\n 3989,\n/**/\n 3988,\n/**/\n 3987,\n/**/\n 3986,\n/**/\n 3985,\n/**/\n 3984,\n/**/\n 3983,\n/**/\n 3982,\n/**/\n 3981,\n/**/\n 3980,\n/**/\n 3979,\n/**/\n 3978,\n/**/\n 3977,\n/**/\n 3976,\n/**/\n 3975,\n/**/\n 3974,\n/**/\n 3973,\n/**/\n 3972,\n/**/\n 3971,\n/**/\n 3970,\n/**/\n 3969,\n/**/\n 3968,\n/**/\n 3967,\n/**/\n 3966,\n/**/\n 3965,\n/**/\n 3964,\n/**/\n 3963,\n/**/\n 3962,\n/**/\n 3961,\n/**/\n 3960,\n/**/\n 3959,\n/**/\n 3958,\n/**/\n 3957,\n/**/\n 3956,\n/**/\n 3955,\n/**/\n 3954,\n/**/\n 3953,\n/**/\n 3952,\n/**/\n 3951,\n/**/\n 3950,\n/**/\n 3949,\n/**/\n 3948,\n/**/\n 3947,\n/**/\n 3946,\n/**/\n 3945,\n/**/\n 3944,\n/**/\n 3943,\n/**/\n 3942,\n/**/\n 3941,\n/**/\n 3940,\n/**/\n 3939,\n/**/\n 3938,\n/**/\n 3937,\n/**/\n 3936,\n/**/\n 3935,\n/**/\n 3934,\n/**/\n 3933,\n/**/\n 3932,\n/**/\n 3931,\n/**/\n 3930,\n/**/\n 3929,\n/**/\n 3928,\n/**/\n 3927,\n/**/\n 3926,\n/**/\n 3925,\n/**/\n 3924,\n/**/\n 3923,\n/**/\n 3922,\n/**/\n 3921,\n/**/\n 3920,\n/**/\n 3919,\n/**/\n 3918,\n/**/\n 3917,\n/**/\n 3916,\n/**/\n 3915,\n/**/\n 3914,\n/**/\n 3913,\n/**/\n 3912,\n/**/\n 3911,\n/**/\n 3910,\n/**/\n 3909,\n/**/\n 3908,\n/**/\n 3907,\n/**/\n 3906,\n/**/\n 3905,\n/**/\n 3904,\n/**/\n 3903,\n/**/\n 3902,\n/**/\n 3901,\n/**/\n 3900,\n/**/\n 3899,\n/**/\n 3898,\n/**/\n 3897,\n/**/\n 3896,\n/**/\n 3895,\n/**/\n 3894,\n/**/\n 3893,\n/**/\n 3892,\n/**/\n 3891,\n/**/\n 3890,\n/**/\n 3889,\n/**/\n 3888,\n/**/\n 3887,\n/**/\n 3886,\n/**/\n 3885,\n/**/\n 3884,\n/**/\n 3883,\n/**/\n 3882,\n/**/\n 3881,\n/**/\n 3880,\n/**/\n 3879,\n/**/\n 3878,\n/**/\n 3877,\n/**/\n 3876,\n/**/\n 3875,\n/**/\n 3874,\n/**/\n 3873,\n/**/\n 3872,\n/**/\n 3871,\n/**/\n 3870,\n/**/\n 3869,\n/**/\n 3868,\n/**/\n 3867,\n/**/\n 3866,\n/**/\n 3865,\n/**/\n 3864,\n/**/\n 3863,\n/**/\n 3862,\n/**/\n 3861,\n/**/\n 3860,\n/**/\n 3859,\n/**/\n 3858,\n/**/\n 3857,\n/**/\n 3856,\n/**/\n 3855,\n/**/\n 3854,\n/**/\n 3853,\n/**/\n 3852,\n/**/\n 3851,\n/**/\n 3850,\n/**/\n 3849,\n/**/\n 3848,\n/**/\n 3847,\n/**/\n 3846,\n/**/\n 3845,\n/**/\n 3844,\n/**/\n 3843,\n/**/\n 3842,\n/**/\n 3841,\n/**/\n 3840,\n/**/\n 3839,\n/**/\n 3838,\n/**/\n 3837,\n/**/\n 3836,\n/**/\n 3835,\n/**/\n 3834,\n/**/\n 3833,\n/**/\n 3832,\n/**/\n 3831,\n/**/\n 3830,\n/**/\n 3829,\n/**/\n 3828,\n/**/\n 3827,\n/**/\n 3826,\n/**/\n 3825,\n/**/\n 3824,\n/**/\n 3823,\n/**/\n 3822,\n/**/\n 3821,\n/**/\n 3820,\n/**/\n 3819,\n/**/\n 3818,\n/**/\n 3817,\n/**/\n 3816,\n/**/\n 3815,\n/**/\n 3814,\n/**/\n 3813,\n/**/\n 3812,\n/**/\n 3811,\n/**/\n 3810,\n/**/\n 3809,\n/**/\n 3808,\n/**/\n 3807,\n/**/\n 3806,\n/**/\n 3805,\n/**/\n 3804,\n/**/\n 3803,\n/**/\n 3802,\n/**/\n 3801,\n/**/\n 3800,\n/**/\n 3799,\n/**/\n 3798,\n/**/\n 3797,\n/**/\n 3796,\n/**/\n 3795,\n/**/\n 3794,\n/**/\n 3793,\n/**/\n 3792,\n/**/\n 3791,\n/**/\n 3790,\n/**/\n 3789,\n/**/\n 3788,\n/**/\n 3787,\n/**/\n 3786,\n/**/\n 3785,\n/**/\n 3784,\n/**/\n 3783,\n/**/\n 3782,\n/**/\n 3781,\n/**/\n 3780,\n/**/\n 3779,\n/**/\n 3778,\n/**/\n 3777,\n/**/\n 3776,\n/**/\n 3775,\n/**/\n 3774,\n/**/\n 3773,\n/**/\n 3772,\n/**/\n 3771,\n/**/\n 3770,\n/**/\n 3769,\n/**/\n 3768,\n/**/\n 3767,\n/**/\n 3766,\n/**/\n 3765,\n/**/\n 3764,\n/**/\n 3763,\n/**/\n 3762,\n/**/\n 3761,\n/**/\n 3760,\n/**/\n 3759,\n/**/\n 3758,\n/**/\n 3757,\n/**/\n 3756,\n/**/\n 3755,\n/**/\n 3754,\n/**/\n 3753,\n/**/\n 3752,\n/**/\n 3751,\n/**/\n 3750,\n/**/\n 3749,\n/**/\n 3748,\n/**/\n 3747,\n/**/\n 3746,\n/**/\n 3745,\n/**/\n 3744,\n/**/\n 3743,\n/**/\n 3742,\n/**/\n 3741,\n/**/\n 3740,\n/**/\n 3739,\n/**/\n 3738,\n/**/\n 3737,\n/**/\n 3736,\n/**/\n 3735,\n/**/\n 3734,\n/**/\n 3733,\n/**/\n 3732,\n/**/\n 3731,\n/**/\n 3730,\n/**/\n 3729,\n/**/\n 3728,\n/**/\n 3727,\n/**/\n 3726,\n/**/\n 3725,\n/**/\n 3724,\n/**/\n 3723,\n/**/\n 3722,\n/**/\n 3721,\n/**/\n 3720,\n/**/\n 3719,\n/**/\n 3718,\n/**/\n 3717,\n/**/\n 3716,\n/**/\n 3715,\n/**/\n 3714,\n/**/\n 3713,\n/**/\n 3712,\n/**/\n 3711,\n/**/\n 3710,\n/**/\n 3709,\n/**/\n 3708,\n/**/\n 3707,\n/**/\n 3706,\n/**/\n 3705,\n/**/\n 3704,\n/**/\n 3703,\n/**/\n 3702,\n/**/\n 3701,\n/**/\n 3700,\n/**/\n 3699,\n/**/\n 3698,\n/**/\n 3697,\n/**/\n 3696,\n/**/\n 3695,\n/**/\n 3694,\n/**/\n 3693,\n/**/\n 3692,\n/**/\n 3691,\n/**/\n 3690,\n/**/\n 3689,\n/**/\n 3688,\n/**/\n 3687,\n/**/\n 3686,\n/**/\n 3685,\n/**/\n 3684,\n/**/\n 3683,\n/**/\n 3682,\n/**/\n 3681,\n/**/\n 3680,\n/**/\n 3679,\n/**/\n 3678,\n/**/\n 3677,\n/**/\n 3676,\n/**/\n 3675,\n/**/\n 3674,\n/**/\n 3673,\n/**/\n 3672,\n/**/\n 3671,\n/**/\n 3670,\n/**/\n 3669,\n/**/\n 3668,\n/**/\n 3667,\n/**/\n 3666,\n/**/\n 3665,\n/**/\n 3664,\n/**/\n 3663,\n/**/\n 3662,\n/**/\n 3661,\n/**/\n 3660,\n/**/\n 3659,\n/**/\n 3658,\n/**/\n 3657,\n/**/\n 3656,\n/**/\n 3655,\n/**/\n 3654,\n/**/\n 3653,\n/**/\n 3652,\n/**/\n 3651,\n/**/\n 3650,\n/**/\n 3649,\n/**/\n 3648,\n/**/\n 3647,\n/**/\n 3646,\n/**/\n 3645,\n/**/\n 3644,\n/**/\n 3643,\n/**/\n 3642,\n/**/\n 3641,\n/**/\n 3640,\n/**/\n 3639,\n/**/\n 3638,\n/**/\n 3637,\n/**/\n 3636,\n/**/\n 3635,\n/**/\n 3634,\n/**/\n 3633,\n/**/\n 3632,\n/**/\n 3631,\n/**/\n 3630,\n/**/\n 3629,\n/**/\n 3628,\n/**/\n 3627,\n/**/\n 3626,\n/**/\n 3625,\n/**/\n 3624,\n/**/\n 3623,\n/**/\n 3622,\n/**/\n 3621,\n/**/\n 3620,\n/**/\n 3619,\n/**/\n 3618,\n/**/\n 3617,\n/**/\n 3616,\n/**/\n 3615,\n/**/\n 3614,\n/**/\n 3613,\n/**/\n 3612,\n/**/\n 3611,\n/**/\n 3610,\n/**/\n 3609,\n/**/\n 3608,\n/**/\n 3607,\n/**/\n 3606,\n/**/\n 3605,\n/**/\n 3604,\n/**/\n 3603,\n/**/\n 3602,\n/**/\n 3601,\n/**/\n 3600,\n/**/\n 3599,\n/**/\n 3598,\n/**/\n 3597,\n/**/\n 3596,\n/**/\n 3595,\n/**/\n 3594,\n/**/\n 3593,\n/**/\n 3592,\n/**/\n 3591,\n/**/\n 3590,\n/**/\n 3589,\n/**/\n 3588,\n/**/\n 3587,\n/**/\n 3586,\n/**/\n 3585,\n/**/\n 3584,\n/**/\n 3583,\n/**/\n 3582,\n/**/\n 3581,\n/**/\n 3580,\n/**/\n 3579,\n/**/\n 3578,\n/**/\n 3577,\n/**/\n 3576,\n/**/\n 3575,\n/**/\n 3574,\n/**/\n 3573,\n/**/\n 3572,\n/**/\n 3571,\n/**/\n 3570,\n/**/\n 3569,\n/**/\n 3568,\n/**/\n 3567,\n/**/\n 3566,\n/**/\n 3565,\n/**/\n 3564,\n/**/\n 3563,\n/**/\n 3562,\n/**/\n 3561,\n/**/\n 3560,\n/**/\n 3559,\n/**/\n 3558,\n/**/\n 3557,\n/**/\n 3556,\n/**/\n 3555,\n/**/\n 3554,\n/**/\n 3553,\n/**/\n 3552,\n/**/\n 3551,\n/**/\n 3550,\n/**/\n 3549,\n/**/\n 3548,\n/**/\n 3547,\n/**/\n 3546,\n/**/\n 3545,\n/**/\n 3544,\n/**/\n 3543,\n/**/\n 3542,\n/**/\n 3541,\n/**/\n 3540,\n/**/\n 3539,\n/**/\n 3538,\n/**/\n 3537,\n/**/\n 3536,\n/**/\n 3535,\n/**/\n 3534,\n/**/\n 3533,\n/**/\n 3532,\n/**/\n 3531,\n/**/\n 3530,\n/**/\n 3529,\n/**/\n 3528,\n/**/\n 3527,\n/**/\n 3526,\n/**/\n 3525,\n/**/\n 3524,\n/**/\n 3523,\n/**/\n 3522,\n/**/\n 3521,\n/**/\n 3520,\n/**/\n 3519,\n/**/\n 3518,\n/**/\n 3517,\n/**/\n 3516,\n/**/\n 3515,\n/**/\n 3514,\n/**/\n 3513,\n/**/\n 3512,\n/**/\n 3511,\n/**/\n 3510,\n/**/\n 3509,\n/**/\n 3508,\n/**/\n 3507,\n/**/\n 3506,\n/**/\n 3505,\n/**/\n 3504,\n/**/\n 3503,\n/**/\n 3502,\n/**/\n 3501,\n/**/\n 3500,\n/**/\n 3499,\n/**/\n 3498,\n/**/\n 3497,\n/**/\n 3496,\n/**/\n 3495,\n/**/\n 3494,\n/**/\n 3493,\n/**/\n 3492,\n/**/\n 3491,\n/**/\n 3490,\n/**/\n 3489,\n/**/\n 3488,\n/**/\n 3487,\n/**/\n 3486,\n/**/\n 3485,\n/**/\n 3484,\n/**/\n 3483,\n/**/\n 3482,\n/**/\n 3481,\n/**/\n 3480,\n/**/\n 3479,\n/**/\n 3478,\n/**/\n 3477,\n/**/\n 3476,\n/**/\n 3475,\n/**/\n 3474,\n/**/\n 3473,\n/**/\n 3472,\n/**/\n 3471,\n/**/\n 3470,\n/**/\n 3469,\n/**/\n 3468,\n/**/\n 3467,\n/**/\n 3466,\n/**/\n 3465,\n/**/\n 3464,\n/**/\n 3463,\n/**/\n 3462,\n/**/\n 3461,\n/**/\n 3460,\n/**/\n 3459,\n/**/\n 3458,\n/**/\n 3457,\n/**/\n 3456,\n/**/\n 3455,\n/**/\n 3454,\n/**/\n 3453,\n/**/\n 3452,\n/**/\n 3451,\n/**/\n 3450,\n/**/\n 3449,\n/**/\n 3448,\n/**/\n 3447,\n/**/\n 3446,\n/**/\n 3445,\n/**/\n 3444,\n/**/\n 3443,\n/**/\n 3442,\n/**/\n 3441,\n/**/\n 3440,\n/**/\n 3439,\n/**/\n 3438,\n/**/\n 3437,\n/**/\n 3436,\n/**/\n 3435,\n/**/\n 3434,\n/**/\n 3433,\n/**/\n 3432,\n/**/\n 3431,\n/**/\n 3430,\n/**/\n 3429,\n/**/\n 3428,\n/**/\n 3427,\n/**/\n 3426,\n/**/\n 3425,\n/**/\n 3424,\n/**/\n 3423,\n/**/\n 3422,\n/**/\n 3421,\n/**/\n 3420,\n/**/\n 3419,\n/**/\n 3418,\n/**/\n 3417,\n/**/\n 3416,\n/**/\n 3415,\n/**/\n 3414,\n/**/\n 3413,\n/**/\n 3412,\n/**/\n 3411,\n/**/\n 3410,\n/**/\n 3409,\n/**/\n 3408,\n/**/\n 3407,\n/**/\n 3406,\n/**/\n 3405,\n/**/\n 3404,\n/**/\n 3403,\n/**/\n 3402,\n/**/\n 3401,\n/**/\n 3400,\n/**/\n 3399,\n/**/\n 3398,\n/**/\n 3397,\n/**/\n 3396,\n/**/\n 3395,\n/**/\n 3394,\n/**/\n 3393,\n/**/\n 3392,\n/**/\n 3391,\n/**/\n 3390,\n/**/\n 3389,\n/**/\n 3388,\n/**/\n 3387,\n/**/\n 3386,\n/**/\n 3385,\n/**/\n 3384,\n/**/\n 3383,\n/**/\n 3382,\n/**/\n 3381,\n/**/\n 3380,\n/**/\n 3379,\n/**/\n 3378,\n/**/\n 3377,\n/**/\n 3376,\n/**/\n 3375,\n/**/\n 3374,\n/**/\n 3373,\n/**/\n 3372,\n/**/\n 3371,\n/**/\n 3370,\n/**/\n 3369,\n/**/\n 3368,\n/**/\n 3367,\n/**/\n 3366,\n/**/\n 3365,\n/**/\n 3364,\n/**/\n 3363,\n/**/\n 3362,\n/**/\n 3361,\n/**/\n 3360,\n/**/\n 3359,\n/**/\n 3358,\n/**/\n 3357,\n/**/\n 3356,\n/**/\n 3355,\n/**/\n 3354,\n/**/\n 3353,\n/**/\n 3352,\n/**/\n 3351,\n/**/\n 3350,\n/**/\n 3349,\n/**/\n 3348,\n/**/\n 3347,\n/**/\n 3346,\n/**/\n 3345,\n/**/\n 3344,\n/**/\n 3343,\n/**/\n 3342,\n/**/\n 3341,\n/**/\n 3340,\n/**/\n 3339,\n/**/\n 3338,\n/**/\n 3337,\n/**/\n 3336,\n/**/\n 3335,\n/**/\n 3334,\n/**/\n 3333,\n/**/\n 3332,\n/**/\n 3331,\n/**/\n 3330,\n/**/\n 3329,\n/**/\n 3328,\n/**/\n 3327,\n/**/\n 3326,\n/**/\n 3325,\n/**/\n 3324,\n/**/\n 3323,\n/**/\n 3322,\n/**/\n 3321,\n/**/\n 3320,\n/**/\n 3319,\n/**/\n 3318,\n/**/\n 3317,\n/**/\n 3316,\n/**/\n 3315,\n/**/\n 3314,\n/**/\n 3313,\n/**/\n 3312,\n/**/\n 3311,\n/**/\n 3310,\n/**/\n 3309,\n/**/\n 3308,\n/**/\n 3307,\n/**/\n 3306,\n/**/\n 3305,\n/**/\n 3304,\n/**/\n 3303,\n/**/\n 3302,\n/**/\n 3301,\n/**/\n 3300,\n/**/\n 3299,\n/**/\n 3298,\n/**/\n 3297,\n/**/\n 3296,\n/**/\n 3295,\n/**/\n 3294,\n/**/\n 3293,\n/**/\n 3292,\n/**/\n 3291,\n/**/\n 3290,\n/**/\n 3289,\n/**/\n 3288,\n/**/\n 3287,\n/**/\n 3286,\n/**/\n 3285,\n/**/\n 3284,\n/**/\n 3283,\n/**/\n 3282,\n/**/\n 3281,\n/**/\n 3280,\n/**/\n 3279,\n/**/\n 3278,\n/**/\n 3277,\n/**/\n 3276,\n/**/\n 3275,\n/**/\n 3274,\n/**/\n 3273,\n/**/\n 3272,\n/**/\n 3271,\n/**/\n 3270,\n/**/\n 3269,\n/**/\n 3268,\n/**/\n 3267,\n/**/\n 3266,\n/**/\n 3265,\n/**/\n 3264,\n/**/\n 3263,\n/**/\n 3262,\n/**/\n 3261,\n/**/\n 3260,\n/**/\n 3259,\n/**/\n 3258,\n/**/\n 3257,\n/**/\n 3256,\n/**/\n 3255,\n/**/\n 3254,\n/**/\n 3253,\n/**/\n 3252,\n/**/\n 3251,\n/**/\n 3250,\n/**/\n 3249,\n/**/\n 3248,\n/**/\n 3247,\n/**/\n 3246,\n/**/\n 3245,\n/**/\n 3244,\n/**/\n 3243,\n/**/\n 3242,\n/**/\n 3241,\n/**/\n 3240,\n/**/\n 3239,\n/**/\n 3238,\n/**/\n 3237,\n/**/\n 3236,\n/**/\n 3235,\n/**/\n 3234,\n/**/\n 3233,\n/**/\n 3232,\n/**/\n 3231,\n/**/\n 3230,\n/**/\n 3229,\n/**/\n 3228,\n/**/\n 3227,\n/**/\n 3226,\n/**/\n 3225,\n/**/\n 3224,\n/**/\n 3223,\n/**/\n 3222,\n/**/\n 3221,\n/**/\n 3220,\n/**/\n 3219,\n/**/\n 3218,\n/**/\n 3217,\n/**/\n 3216,\n/**/\n 3215,\n/**/\n 3214,\n/**/\n 3213,\n/**/\n 3212,\n/**/\n 3211,\n/**/\n 3210,\n/**/\n 3209,\n/**/\n 3208,\n/**/\n 3207,\n/**/\n 3206,\n/**/\n 3205,\n/**/\n 3204,\n/**/\n 3203,\n/**/\n 3202,\n/**/\n 3201,\n/**/\n 3200,\n/**/\n 3199,\n/**/\n 3198,\n/**/\n 3197,\n/**/\n 3196,\n/**/\n 3195,\n/**/\n 3194,\n/**/\n 3193,\n/**/\n 3192,\n/**/\n 3191,\n/**/\n 3190,\n/**/\n 3189,\n/**/\n 3188,\n/**/\n 3187,\n/**/\n 3186,\n/**/\n 3185,\n/**/\n 3184,\n/**/\n 3183,\n/**/\n 3182,\n/**/\n 3181,\n/**/\n 3180,\n/**/\n 3179,\n/**/\n 3178,\n/**/\n 3177,\n/**/\n 3176,\n/**/\n 3175,\n/**/\n 3174,\n/**/\n 3173,\n/**/\n 3172,\n/**/\n 3171,\n/**/\n 3170,\n/**/\n 3169,\n/**/\n 3168,\n/**/\n 3167,\n/**/\n 3166,\n/**/\n 3165,\n/**/\n 3164,\n/**/\n 3163,\n/**/\n 3162,\n/**/\n 3161,\n/**/\n 3160,\n/**/\n 3159,\n/**/\n 3158,\n/**/\n 3157,\n/**/\n 3156,\n/**/\n 3155,\n/**/\n 3154,\n/**/\n 3153,\n/**/\n 3152,\n/**/\n 3151,\n/**/\n 3150,\n/**/\n 3149,\n/**/\n 3148,\n/**/\n 3147,\n/**/\n 3146,\n/**/\n 3145,\n/**/\n 3144,\n/**/\n 3143,\n/**/\n 3142,\n/**/\n 3141,\n/**/\n 3140,\n/**/\n 3139,\n/**/\n 3138,\n/**/\n 3137,\n/**/\n 3136,\n/**/\n 3135,\n/**/\n 3134,\n/**/\n 3133,\n/**/\n 3132,\n/**/\n 3131,\n/**/\n 3130,\n/**/\n 3129,\n/**/\n 3128,\n/**/\n 3127,\n/**/\n 3126,\n/**/\n 3125,\n/**/\n 3124,\n/**/\n 3123,\n/**/\n 3122,\n/**/\n 3121,\n/**/\n 3120,\n/**/\n 3119,\n/**/\n 3118,\n/**/\n 3117,\n/**/\n 3116,\n/**/\n 3115,\n/**/\n 3114,\n/**/\n 3113,\n/**/\n 3112,\n/**/\n 3111,\n/**/\n 3110,\n/**/\n 3109,\n/**/\n 3108,\n/**/\n 3107,\n/**/\n 3106,\n/**/\n 3105,\n/**/\n 3104,\n/**/\n 3103,\n/**/\n 3102,\n/**/\n 3101,\n/**/\n 3100,\n/**/\n 3099,\n/**/\n 3098,\n/**/\n 3097,\n/**/\n 3096,\n/**/\n 3095,\n/**/\n 3094,\n/**/\n 3093,\n/**/\n 3092,\n/**/\n 3091,\n/**/\n 3090,\n/**/\n 3089,\n/**/\n 3088,\n/**/\n 3087,\n/**/\n 3086,\n/**/\n 3085,\n/**/\n 3084,\n/**/\n 3083,\n/**/\n 3082,\n/**/\n 3081,\n/**/\n 3080,\n/**/\n 3079,\n/**/\n 3078,\n/**/\n 3077,\n/**/\n 3076,\n/**/\n 3075,\n/**/\n 3074,\n/**/\n 3073,\n/**/\n 3072,\n/**/\n 3071,\n/**/\n 3070,\n/**/\n 3069,\n/**/\n 3068,\n/**/\n 3067,\n/**/\n 3066,\n/**/\n 3065,\n/**/\n 3064,\n/**/\n 3063,\n/**/\n 3062,\n/**/\n 3061,\n/**/\n 3060,\n/**/\n 3059,\n/**/\n 3058,\n/**/\n 3057,\n/**/\n 3056,\n/**/\n 3055,\n/**/\n 3054,\n/**/\n 3053,\n/**/\n 3052,\n/**/\n 3051,\n/**/\n 3050,\n/**/\n 3049,\n/**/\n 3048,\n/**/\n 3047,\n/**/\n 3046,\n/**/\n 3045,\n/**/\n 3044,\n/**/\n 3043,\n/**/\n 3042,\n/**/\n 3041,\n/**/\n 3040,\n/**/\n 3039,\n/**/\n 3038,\n/**/\n 3037,\n/**/\n 3036,\n/**/\n 3035,\n/**/\n 3034,\n/**/\n 3033,\n/**/\n 3032,\n/**/\n 3031,\n/**/\n 3030,\n/**/\n 3029,\n/**/\n 3028,\n/**/\n 3027,\n/**/\n 3026,\n/**/\n 3025,\n/**/\n 3024,\n/**/\n 3023,\n/**/\n 3022,\n/**/\n 3021,\n/**/\n 3020,\n/**/\n 3019,\n/**/\n 3018,\n/**/\n 3017,\n/**/\n 3016,\n/**/\n 3015,\n/**/\n 3014,\n/**/\n 3013,\n/**/\n 3012,\n/**/\n 3011,\n/**/\n 3010,\n/**/\n 3009,\n/**/\n 3008,\n/**/\n 3007,\n/**/\n 3006,\n/**/\n 3005,\n/**/\n 3004,\n/**/\n 3003,\n/**/\n 3002,\n/**/\n 3001,\n/**/\n 3000,\n/**/\n 2999,\n/**/\n 2998,\n/**/\n 2997,\n/**/\n 2996,\n/**/\n 2995,\n/**/\n 2994,\n/**/\n 2993,\n/**/\n 2992,\n/**/\n 2991,\n/**/\n 2990,\n/**/\n 2989,\n/**/\n 2988,\n/**/\n 2987,\n/**/\n 2986,\n/**/\n 2985,\n/**/\n 2984,\n/**/\n 2983,\n/**/\n 2982,\n/**/\n 2981,\n/**/\n 2980,\n/**/\n 2979,\n/**/\n 2978,\n/**/\n 2977,\n/**/\n 2976,\n/**/\n 2975,\n/**/\n 2974,\n/**/\n 2973,\n/**/\n 2972,\n/**/\n 2971,\n/**/\n 2970,\n/**/\n 2969,\n/**/\n 2968,\n/**/\n 2967,\n/**/\n 2966,\n/**/\n 2965,\n/**/\n 2964,\n/**/\n 2963,\n/**/\n 2962,\n/**/\n 2961,\n/**/\n 2960,\n/**/\n 2959,\n/**/\n 2958,\n/**/\n 2957,\n/**/\n 2956,\n/**/\n 2955,\n/**/\n 2954,\n/**/\n 2953,\n/**/\n 2952,\n/**/\n 2951,\n/**/\n 2950,\n/**/\n 2949,\n/**/\n 2948,\n/**/\n 2947,\n/**/\n 2946,\n/**/\n 2945,\n/**/\n 2944,\n/**/\n 2943,\n/**/\n 2942,\n/**/\n 2941,\n/**/\n 2940,\n/**/\n 2939,\n/**/\n 2938,\n/**/\n 2937,\n/**/\n 2936,\n/**/\n 2935,\n/**/\n 2934,\n/**/\n 2933,\n/**/\n 2932,\n/**/\n 2931,\n/**/\n 2930,\n/**/\n 2929,\n/**/\n 2928,\n/**/\n 2927,\n/**/\n 2926,\n/**/\n 2925,\n/**/\n 2924,\n/**/\n 2923,\n/**/\n 2922,\n/**/\n 2921,\n/**/\n 2920,\n/**/\n 2919,\n/**/\n 2918,\n/**/\n 2917,\n/**/\n 2916,\n/**/\n 2915,\n/**/\n 2914,\n/**/\n 2913,\n/**/\n 2912,\n/**/\n 2911,\n/**/\n 2910,\n/**/\n 2909,\n/**/\n 2908,\n/**/\n 2907,\n/**/\n 2906,\n/**/\n 2905,\n/**/\n 2904,\n/**/\n 2903,\n/**/\n 2902,\n/**/\n 2901,\n/**/\n 2900,\n/**/\n 2899,\n/**/\n 2898,\n/**/\n 2897,\n/**/\n 2896,\n/**/\n 2895,\n/**/\n 2894,\n/**/\n 2893,\n/**/\n 2892,\n/**/\n 2891,\n/**/\n 2890,\n/**/\n 2889,\n/**/\n 2888,\n/**/\n 2887,\n/**/\n 2886,\n/**/\n 2885,\n/**/\n 2884,\n/**/\n 2883,\n/**/\n 2882,\n/**/\n 2881,\n/**/\n 2880,\n/**/\n 2879,\n/**/\n 2878,\n/**/\n 2877,\n/**/\n 2876,\n/**/\n 2875,\n/**/\n 2874,\n/**/\n 2873,\n/**/\n 2872,\n/**/\n 2871,\n/**/\n 2870,\n/**/\n 2869,\n/**/\n 2868,\n/**/\n 2867,\n/**/\n 2866,\n/**/\n 2865,\n/**/\n 2864,\n/**/\n 2863,\n/**/\n 2862,\n/**/\n 2861,\n/**/\n 2860,\n/**/\n 2859,\n/**/\n 2858,\n/**/\n 2857,\n/**/\n 2856,\n/**/\n 2855,\n/**/\n 2854,\n/**/\n 2853,\n/**/\n 2852,\n/**/\n 2851,\n/**/\n 2850,\n/**/\n 2849,\n/**/\n 2848,\n/**/\n 2847,\n/**/\n 2846,\n/**/\n 2845,\n/**/\n 2844,\n/**/\n 2843,\n/**/\n 2842,\n/**/\n 2841,\n/**/\n 2840,\n/**/\n 2839,\n/**/\n 2838,\n/**/\n 2837,\n/**/\n 2836,\n/**/\n 2835,\n/**/\n 2834,\n/**/\n 2833,\n/**/\n 2832,\n/**/\n 2831,\n/**/\n 2830,\n/**/\n 2829,\n/**/\n 2828,\n/**/\n 2827,\n/**/\n 2826,\n/**/\n 2825,\n/**/\n 2824,\n/**/\n 2823,\n/**/\n 2822,\n/**/\n 2821,\n/**/\n 2820,\n/**/\n 2819,\n/**/\n 2818,\n/**/\n 2817,\n/**/\n 2816,\n/**/\n 2815,\n/**/\n 2814,\n/**/\n 2813,\n/**/\n 2812,\n/**/\n 2811,\n/**/\n 2810,\n/**/\n 2809,\n/**/\n 2808,\n/**/\n 2807,\n/**/\n 2806,\n/**/\n 2805,\n/**/\n 2804,\n/**/\n 2803,\n/**/\n 2802,\n/**/\n 2801,\n/**/\n 2800,\n/**/\n 2799,\n/**/\n 2798,\n/**/\n 2797,\n/**/\n 2796,\n/**/\n 2795,\n/**/\n 2794,\n/**/\n 2793,\n/**/\n 2792,\n/**/\n 2791,\n/**/\n 2790,\n/**/\n 2789,\n/**/\n 2788,\n/**/\n 2787,\n/**/\n 2786,\n/**/\n 2785,\n/**/\n 2784,\n/**/\n 2783,\n/**/\n 2782,\n/**/\n 2781,\n/**/\n 2780,\n/**/\n 2779,\n/**/\n 2778,\n/**/\n 2777,\n/**/\n 2776,\n/**/\n 2775,\n/**/\n 2774,\n/**/\n 2773,\n/**/\n 2772,\n/**/\n 2771,\n/**/\n 2770,\n/**/\n 2769,\n/**/\n 2768,\n/**/\n 2767,\n/**/\n 2766,\n/**/\n 2765,\n/**/\n 2764,\n/**/\n 2763,\n/**/\n 2762,\n/**/\n 2761,\n/**/\n 2760,\n/**/\n 2759,\n/**/\n 2758,\n/**/\n 2757,\n/**/\n 2756,\n/**/\n 2755,\n/**/\n 2754,\n/**/\n 2753,\n/**/\n 2752,\n/**/\n 2751,\n/**/\n 2750,\n/**/\n 2749,\n/**/\n 2748,\n/**/\n 2747,\n/**/\n 2746,\n/**/\n 2745,\n/**/\n 2744,\n/**/\n 2743,\n/**/\n 2742,\n/**/\n 2741,\n/**/\n 2740,\n/**/\n 2739,\n/**/\n 2738,\n/**/\n 2737,\n/**/\n 2736,\n/**/\n 2735,\n/**/\n 2734,\n/**/\n 2733,\n/**/\n 2732,\n/**/\n 2731,\n/**/\n 2730,\n/**/\n 2729,\n/**/\n 2728,\n/**/\n 2727,\n/**/\n 2726,\n/**/\n 2725,\n/**/\n 2724,\n/**/\n 2723,\n/**/\n 2722,\n/**/\n 2721,\n/**/\n 2720,\n/**/\n 2719,\n/**/\n 2718,\n/**/\n 2717,\n/**/\n 2716,\n/**/\n 2715,\n/**/\n 2714,\n/**/\n 2713,\n/**/\n 2712,\n/**/\n 2711,\n/**/\n 2710,\n/**/\n 2709,\n/**/\n 2708,\n/**/\n 2707,\n/**/\n 2706,\n/**/\n 2705,\n/**/\n 2704,\n/**/\n 2703,\n/**/\n 2702,\n/**/\n 2701,\n/**/\n 2700,\n/**/\n 2699,\n/**/\n 2698,\n/**/\n 2697,\n/**/\n 2696,\n/**/\n 2695,\n/**/\n 2694,\n/**/\n 2693,\n/**/\n 2692,\n/**/\n 2691,\n/**/\n 2690,\n/**/\n 2689,\n/**/\n 2688,\n/**/\n 2687,\n/**/\n 2686,\n/**/\n 2685,\n/**/\n 2684,\n/**/\n 2683,\n/**/\n 2682,\n/**/\n 2681,\n/**/\n 2680,\n/**/\n 2679,\n/**/\n 2678,\n/**/\n 2677,\n/**/\n 2676,\n/**/\n 2675,\n/**/\n 2674,\n/**/\n 2673,\n/**/\n 2672,\n/**/\n 2671,\n/**/\n 2670,\n/**/\n 2669,\n/**/\n 2668,\n/**/\n 2667,\n/**/\n 2666,\n/**/\n 2665,\n/**/\n 2664,\n/**/\n 2663,\n/**/\n 2662,\n/**/\n 2661,\n/**/\n 2660,\n/**/\n 2659,\n/**/\n 2658,\n/**/\n 2657,\n/**/\n 2656,\n/**/\n 2655,\n/**/\n 2654,\n/**/\n 2653,\n/**/\n 2652,\n/**/\n 2651,\n/**/\n 2650,\n/**/\n 2649,\n/**/\n 2648,\n/**/\n 2647,\n/**/\n 2646,\n/**/\n 2645,\n/**/\n 2644,\n/**/\n 2643,\n/**/\n 2642,\n/**/\n 2641,\n/**/\n 2640,\n/**/\n 2639,\n/**/\n 2638,\n/**/\n 2637,\n/**/\n 2636,\n/**/\n 2635,\n/**/\n 2634,\n/**/\n 2633,\n/**/\n 2632,\n/**/\n 2631,\n/**/\n 2630,\n/**/\n 2629,\n/**/\n 2628,\n/**/\n 2627,\n/**/\n 2626,\n/**/\n 2625,\n/**/\n 2624,\n/**/\n 2623,\n/**/\n 2622,\n/**/\n 2621,\n/**/\n 2620,\n/**/\n 2619,\n/**/\n 2618,\n/**/\n 2617,\n/**/\n 2616,\n/**/\n 2615,\n/**/\n 2614,\n/**/\n 2613,\n/**/\n 2612,\n/**/\n 2611,\n/**/\n 2610,\n/**/\n 2609,\n/**/\n 2608,\n/**/\n 2607,\n/**/\n 2606,\n/**/\n 2605,\n/**/\n 2604,\n/**/\n 2603,\n/**/\n 2602,\n/**/\n 2601,\n/**/\n 2600,\n/**/\n 2599,\n/**/\n 2598,\n/**/\n 2597,\n/**/\n 2596,\n/**/\n 2595,\n/**/\n 2594,\n/**/\n 2593,\n/**/\n 2592,\n/**/\n 2591,\n/**/\n 2590,\n/**/\n 2589,\n/**/\n 2588,\n/**/\n 2587,\n/**/\n 2586,\n/**/\n 2585,\n/**/\n 2584,\n/**/\n 2583,\n/**/\n 2582,\n/**/\n 2581,\n/**/\n 2580,\n/**/\n 2579,\n/**/\n 2578,\n/**/\n 2577,\n/**/\n 2576,\n/**/\n 2575,\n/**/\n 2574,\n/**/\n 2573,\n/**/\n 2572,\n/**/\n 2571,\n/**/\n 2570,\n/**/\n 2569,\n/**/\n 2568,\n/**/\n 2567,\n/**/\n 2566,\n/**/\n 2565,\n/**/\n 2564,\n/**/\n 2563,\n/**/\n 2562,\n/**/\n 2561,\n/**/\n 2560,\n/**/\n 2559,\n/**/\n 2558,\n/**/\n 2557,\n/**/\n 2556,\n/**/\n 2555,\n/**/\n 2554,\n/**/\n 2553,\n/**/\n 2552,\n/**/\n 2551,\n/**/\n 2550,\n/**/\n 2549,\n/**/\n 2548,\n/**/\n 2547,\n/**/\n 2546,\n/**/\n 2545,\n/**/\n 2544,\n/**/\n 2543,\n/**/\n 2542,\n/**/\n 2541,\n/**/\n 2540,\n/**/\n 2539,\n/**/\n 2538,\n/**/\n 2537,\n/**/\n 2536,\n/**/\n 2535,\n/**/\n 2534,\n/**/\n 2533,\n/**/\n 2532,\n/**/\n 2531,\n/**/\n 2530,\n/**/\n 2529,\n/**/\n 2528,\n/**/\n 2527,\n/**/\n 2526,\n/**/\n 2525,\n/**/\n 2524,\n/**/\n 2523,\n/**/\n 2522,\n/**/\n 2521,\n/**/\n 2520,\n/**/\n 2519,\n/**/\n 2518,\n/**/\n 2517,\n/**/\n 2516,\n/**/\n 2515,\n/**/\n 2514,\n/**/\n 2513,\n/**/\n 2512,\n/**/\n 2511,\n/**/\n 2510,\n/**/\n 2509,\n/**/\n 2508,\n/**/\n 2507,\n/**/\n 2506,\n/**/\n 2505,\n/**/\n 2504,\n/**/\n 2503,\n/**/\n 2502,\n/**/\n 2501,\n/**/\n 2500,\n/**/\n 2499,\n/**/\n 2498,\n/**/\n 2497,\n/**/\n 2496,\n/**/\n 2495,\n/**/\n 2494,\n/**/\n 2493,\n/**/\n 2492,\n/**/\n 2491,\n/**/\n 2490,\n/**/\n 2489,\n/**/\n 2488,\n/**/\n 2487,\n/**/\n 2486,\n/**/\n 2485,\n/**/\n 2484,\n/**/\n 2483,\n/**/\n 2482,\n/**/\n 2481,\n/**/\n 2480,\n/**/\n 2479,\n/**/\n 2478,\n/**/\n 2477,\n/**/\n 2476,\n/**/\n 2475,\n/**/\n 2474,\n/**/\n 2473,\n/**/\n 2472,\n/**/\n 2471,\n/**/\n 2470,\n/**/\n 2469,\n/**/\n 2468,\n/**/\n 2467,\n/**/\n 2466,\n/**/\n 2465,\n/**/\n 2464,\n/**/\n 2463,\n/**/\n 2462,\n/**/\n 2461,\n/**/\n 2460,\n/**/\n 2459,\n/**/\n 2458,\n/**/\n 2457,\n/**/\n 2456,\n/**/\n 2455,\n/**/\n 2454,\n/**/\n 2453,\n/**/\n 2452,\n/**/\n 2451,\n/**/\n 2450,\n/**/\n 2449,\n/**/\n 2448,\n/**/\n 2447,\n/**/\n 2446,\n/**/\n 2445,\n/**/\n 2444,\n/**/\n 2443,\n/**/\n 2442,\n/**/\n 2441,\n/**/\n 2440,\n/**/\n 2439,\n/**/\n 2438,\n/**/\n 2437,\n/**/\n 2436,\n/**/\n 2435,\n/**/\n 2434,\n/**/\n 2433,\n/**/\n 2432,\n/**/\n 2431,\n/**/\n 2430,\n/**/\n 2429,\n/**/\n 2428,\n/**/\n 2427,\n/**/\n 2426,\n/**/\n 2425,\n/**/\n 2424,\n/**/\n 2423,\n/**/\n 2422,\n/**/\n 2421,\n/**/\n 2420,\n/**/\n 2419,\n/**/\n 2418,\n/**/\n 2417,\n/**/\n 2416,\n/**/\n 2415,\n/**/\n 2414,\n/**/\n 2413,\n/**/\n 2412,\n/**/\n 2411,\n/**/\n 2410,\n/**/\n 2409,\n/**/\n 2408,\n/**/\n 2407,\n/**/\n 2406,\n/**/\n 2405,\n/**/\n 2404,\n/**/\n 2403,\n/**/\n 2402,\n/**/\n 2401,\n/**/\n 2400,\n/**/\n 2399,\n/**/\n 2398,\n/**/\n 2397,\n/**/\n 2396,\n/**/\n 2395,\n/**/\n 2394,\n/**/\n 2393,\n/**/\n 2392,\n/**/\n 2391,\n/**/\n 2390,\n/**/\n 2389,\n/**/\n 2388,\n/**/\n 2387,\n/**/\n 2386,\n/**/\n 2385,\n/**/\n 2384,\n/**/\n 2383,\n/**/\n 2382,\n/**/\n 2381,\n/**/\n 2380,\n/**/\n 2379,\n/**/\n 2378,\n/**/\n 2377,\n/**/\n 2376,\n/**/\n 2375,\n/**/\n 2374,\n/**/\n 2373,\n/**/\n 2372,\n/**/\n 2371,\n/**/\n 2370,\n/**/\n 2369,\n/**/\n 2368,\n/**/\n 2367,\n/**/\n 2366,\n/**/\n 2365,\n/**/\n 2364,\n/**/\n 2363,\n/**/\n 2362,\n/**/\n 2361,\n/**/\n 2360,\n/**/\n 2359,\n/**/\n 2358,\n/**/\n 2357,\n/**/\n 2356,\n/**/\n 2355,\n/**/\n 2354,\n/**/\n 2353,\n/**/\n 2352,\n/**/\n 2351,\n/**/\n 2350,\n/**/\n 2349,\n/**/\n 2348,\n/**/\n 2347,\n/**/\n 2346,\n/**/\n 2345,\n/**/\n 2344,\n/**/\n 2343,\n/**/\n 2342,\n/**/\n 2341,\n/**/\n 2340,\n/**/\n 2339,\n/**/\n 2338,\n/**/\n 2337,\n/**/\n 2336,\n/**/\n 2335,\n/**/\n 2334,\n/**/\n 2333,\n/**/\n 2332,\n/**/\n 2331,\n/**/\n 2330,\n/**/\n 2329,\n/**/\n 2328,\n/**/\n 2327,\n/**/\n 2326,\n/**/\n 2325,\n/**/\n 2324,\n/**/\n 2323,\n/**/\n 2322,\n/**/\n 2321,\n/**/\n 2320,\n/**/\n 2319,\n/**/\n 2318,\n/**/\n 2317,\n/**/\n 2316,\n/**/\n 2315,\n/**/\n 2314,\n/**/\n 2313,\n/**/\n 2312,\n/**/\n 2311,\n/**/\n 2310,\n/**/\n 2309,\n/**/\n 2308,\n/**/\n 2307,\n/**/\n 2306,\n/**/\n 2305,\n/**/\n 2304,\n/**/\n 2303,\n/**/\n 2302,\n/**/\n 2301,\n/**/\n 2300,\n/**/\n 2299,\n/**/\n 2298,\n/**/\n 2297,\n/**/\n 2296,\n/**/\n 2295,\n/**/\n 2294,\n/**/\n 2293,\n/**/\n 2292,\n/**/\n 2291,\n/**/\n 2290,\n/**/\n 2289,\n/**/\n 2288,\n/**/\n 2287,\n/**/\n 2286,\n/**/\n 2285,\n/**/\n 2284,\n/**/\n 2283,\n/**/\n 2282,\n/**/\n 2281,\n/**/\n 2280,\n/**/\n 2279,\n/**/\n 2278,\n/**/\n 2277,\n/**/\n 2276,\n/**/\n 2275,\n/**/\n 2274,\n/**/\n 2273,\n/**/\n 2272,\n/**/\n 2271,\n/**/\n 2270,\n/**/\n 2269,\n/**/\n 2268,\n/**/\n 2267,\n/**/\n 2266,\n/**/\n 2265,\n/**/\n 2264,\n/**/\n 2263,\n/**/\n 2262,\n/**/\n 2261,\n/**/\n 2260,\n/**/\n 2259,\n/**/\n 2258,\n/**/\n 2257,\n/**/\n 2256,\n/**/\n 2255,\n/**/\n 2254,\n/**/\n 2253,\n/**/\n 2252,\n/**/\n 2251,\n/**/\n 2250,\n/**/\n 2249,\n/**/\n 2248,\n/**/\n 2247,\n/**/\n 2246,\n/**/\n 2245,\n/**/\n 2244,\n/**/\n 2243,\n/**/\n 2242,\n/**/\n 2241,\n/**/\n 2240,\n/**/\n 2239,\n/**/\n 2238,\n/**/\n 2237,\n/**/\n 2236,\n/**/\n 2235,\n/**/\n 2234,\n/**/\n 2233,\n/**/\n 2232,\n/**/\n 2231,\n/**/\n 2230,\n/**/\n 2229,\n/**/\n 2228,\n/**/\n 2227,\n/**/\n 2226,\n/**/\n 2225,\n/**/\n 2224,\n/**/\n 2223,\n/**/\n 2222,\n/**/\n 2221,\n/**/\n 2220,\n/**/\n 2219,\n/**/\n 2218,\n/**/\n 2217,\n/**/\n 2216,\n/**/\n 2215,\n/**/\n 2214,\n/**/\n 2213,\n/**/\n 2212,\n/**/\n 2211,\n/**/\n 2210,\n/**/\n 2209,\n/**/\n 2208,\n/**/\n 2207,\n/**/\n 2206,\n/**/\n 2205,\n/**/\n 2204,\n/**/\n 2203,\n/**/\n 2202,\n/**/\n 2201,\n/**/\n 2200,\n/**/\n 2199,\n/**/\n 2198,\n/**/\n 2197,\n/**/\n 2196,\n/**/\n 2195,\n/**/\n 2194,\n/**/\n 2193,\n/**/\n 2192,\n/**/\n 2191,\n/**/\n 2190,\n/**/\n 2189,\n/**/\n 2188,\n/**/\n 2187,\n/**/\n 2186,\n/**/\n 2185,\n/**/\n 2184,\n/**/\n 2183,\n/**/\n 2182,\n/**/\n 2181,\n/**/\n 2180,\n/**/\n 2179,\n/**/\n 2178,\n/**/\n 2177,\n/**/\n 2176,\n/**/\n 2175,\n/**/\n 2174,\n/**/\n 2173,\n/**/\n 2172,\n/**/\n 2171,\n/**/\n 2170,\n/**/\n 2169,\n/**/\n 2168,\n/**/\n 2167,\n/**/\n 2166,\n/**/\n 2165,\n/**/\n 2164,\n/**/\n 2163,\n/**/\n 2162,\n/**/\n 2161,\n/**/\n 2160,\n/**/\n 2159,\n/**/\n 2158,\n/**/\n 2157,\n/**/\n 2156,\n/**/\n 2155,\n/**/\n 2154,\n/**/\n 2153,\n/**/\n 2152,\n/**/\n 2151,\n/**/\n 2150,\n/**/\n 2149,\n/**/\n 2148,\n/**/\n 2147,\n/**/\n 2146,\n/**/\n 2145,\n/**/\n 2144,\n/**/\n 2143,\n/**/\n 2142,\n/**/\n 2141,\n/**/\n 2140,\n/**/\n 2139,\n/**/\n 2138,\n/**/\n 2137,\n/**/\n 2136,\n/**/\n 2135,\n/**/\n 2134,\n/**/\n 2133,\n/**/\n 2132,\n/**/\n 2131,\n/**/\n 2130,\n/**/\n 2129,\n/**/\n 2128,\n/**/\n 2127,\n/**/\n 2126,\n/**/\n 2125,\n/**/\n 2124,\n/**/\n 2123,\n/**/\n 2122,\n/**/\n 2121,\n/**/\n 2120,\n/**/\n 2119,\n/**/\n 2118,\n/**/\n 2117,\n/**/\n 2116,\n/**/\n 2115,\n/**/\n 2114,\n/**/\n 2113,\n/**/\n 2112,\n/**/\n 2111,\n/**/\n 2110,\n/**/\n 2109,\n/**/\n 2108,\n/**/\n 2107,\n/**/\n 2106,\n/**/\n 2105,\n/**/\n 2104,\n/**/\n 2103,\n/**/\n 2102,\n/**/\n 2101,\n/**/\n 2100,\n/**/\n 2099,\n/**/\n 2098,\n/**/\n 2097,\n/**/\n 2096,\n/**/\n 2095,\n/**/\n 2094,\n/**/\n 2093,\n/**/\n 2092,\n/**/\n 2091,\n/**/\n 2090,\n/**/\n 2089,\n/**/\n 2088,\n/**/\n 2087,\n/**/\n 2086,\n/**/\n 2085,\n/**/\n 2084,\n/**/\n 2083,\n/**/\n 2082,\n/**/\n 2081,\n/**/\n 2080,\n/**/\n 2079,\n/**/\n 2078,\n/**/\n 2077,\n/**/\n 2076,\n/**/\n 2075,\n/**/\n 2074,\n/**/\n 2073,\n/**/\n 2072,\n/**/\n 2071,\n/**/\n 2070,\n/**/\n 2069,\n/**/\n 2068,\n/**/\n 2067,\n/**/\n 2066,\n/**/\n 2065,\n/**/\n 2064,\n/**/\n 2063,\n/**/\n 2062,\n/**/\n 2061,\n/**/\n 2060,\n/**/\n 2059,\n/**/\n 2058,\n/**/\n 2057,\n/**/\n 2056,\n/**/\n 2055,\n/**/\n 2054,\n/**/\n 2053,\n/**/\n 2052,\n/**/\n 2051,\n/**/\n 2050,\n/**/\n 2049,\n/**/\n 2048,\n/**/\n 2047,\n/**/\n 2046,\n/**/\n 2045,\n/**/\n 2044,\n/**/\n 2043,\n/**/\n 2042,\n/**/\n 2041,\n/**/\n 2040,\n/**/\n 2039,\n/**/\n 2038,\n/**/\n 2037,\n/**/\n 2036,\n/**/\n 2035,\n/**/\n 2034,\n/**/\n 2033,\n/**/\n 2032,\n/**/\n 2031,\n/**/\n 2030,\n/**/\n 2029,\n/**/\n 2028,\n/**/\n 2027,\n/**/\n 2026,\n/**/\n 2025,\n/**/\n 2024,\n/**/\n 2023,\n/**/\n 2022,\n/**/\n 2021,\n/**/\n 2020,\n/**/\n 2019,\n/**/\n 2018,\n/**/\n 2017,\n/**/\n 2016,\n/**/\n 2015,\n/**/\n 2014,\n/**/\n 2013,\n/**/\n 2012,\n/**/\n 2011,\n/**/\n 2010,\n/**/\n 2009,\n/**/\n 2008,\n/**/\n 2007,\n/**/\n 2006,\n/**/\n 2005,\n/**/\n 2004,\n/**/\n 2003,\n/**/\n 2002,\n/**/\n 2001,\n/**/\n 2000,\n/**/\n 1999,\n/**/\n 1998,\n/**/\n 1997,\n/**/\n 1996,\n/**/\n 1995,\n/**/\n 1994,\n/**/\n 1993,\n/**/\n 1992,\n/**/\n 1991,\n/**/\n 1990,\n/**/\n 1989,\n/**/\n 1988,\n/**/\n 1987,\n/**/\n 1986,\n/**/\n 1985,\n/**/\n 1984,\n/**/\n 1983,\n/**/\n 1982,\n/**/\n 1981,\n/**/\n 1980,\n/**/\n 1979,\n/**/\n 1978,\n/**/\n 1977,\n/**/\n 1976,\n/**/\n 1975,\n/**/\n 1974,\n/**/\n 1973,\n/**/\n 1972,\n/**/\n 1971,\n/**/\n 1970,\n/**/\n 1969,\n/**/\n 1968,\n/**/\n 1967,\n/**/\n 1966,\n/**/\n 1965,\n/**/\n 1964,\n/**/\n 1963,\n/**/\n 1962,\n/**/\n 1961,\n/**/\n 1960,\n/**/\n 1959,\n/**/\n 1958,\n/**/\n 1957,\n/**/\n 1956,\n/**/\n 1955,\n/**/\n 1954,\n/**/\n 1953,\n/**/\n 1952,\n/**/\n 1951,\n/**/\n 1950,\n/**/\n 1949,\n/**/\n 1948,\n/**/\n 1947,\n/**/\n 1946,\n/**/\n 1945,\n/**/\n 1944,\n/**/\n 1943,\n/**/\n 1942,\n/**/\n 1941,\n/**/\n 1940,\n/**/\n 1939,\n/**/\n 1938,\n/**/\n 1937,\n/**/\n 1936,\n/**/\n 1935,\n/**/\n 1934,\n/**/\n 1933,\n/**/\n 1932,\n/**/\n 1931,\n/**/\n 1930,\n/**/\n 1929,\n/**/\n 1928,\n/**/\n 1927,\n/**/\n 1926,\n/**/\n 1925,\n/**/\n 1924,\n/**/\n 1923,\n/**/\n 1922,\n/**/\n 1921,\n/**/\n 1920,\n/**/\n 1919,\n/**/\n 1918,\n/**/\n 1917,\n/**/\n 1916,\n/**/\n 1915,\n/**/\n 1914,\n/**/\n 1913,\n/**/\n 1912,\n/**/\n 1911,\n/**/\n 1910,\n/**/\n 1909,\n/**/\n 1908,\n/**/\n 1907,\n/**/\n 1906,\n/**/\n 1905,\n/**/\n 1904,\n/**/\n 1903,\n/**/\n 1902,\n/**/\n 1901,\n/**/\n 1900,\n/**/\n 1899,\n/**/\n 1898,\n/**/\n 1897,\n/**/\n 1896,\n/**/\n 1895,\n/**/\n 1894,\n/**/\n 1893,\n/**/\n 1892,\n/**/\n 1891,\n/**/\n 1890,\n/**/\n 1889,\n/**/\n 1888,\n/**/\n 1887,\n/**/\n 1886,\n/**/\n 1885,\n/**/\n 1884,\n/**/\n 1883,\n/**/\n 1882,\n/**/\n 1881,\n/**/\n 1880,\n/**/\n 1879,\n/**/\n 1878,\n/**/\n 1877,\n/**/\n 1876,\n/**/\n 1875,\n/**/\n 1874,\n/**/\n 1873,\n/**/\n 1872,\n/**/\n 1871,\n/**/\n 1870,\n/**/\n 1869,\n/**/\n 1868,\n/**/\n 1867,\n/**/\n 1866,\n/**/\n 1865,\n/**/\n 1864,\n/**/\n 1863,\n/**/\n 1862,\n/**/\n 1861,\n/**/\n 1860,\n/**/\n 1859,\n/**/\n 1858,\n/**/\n 1857,\n/**/\n 1856,\n/**/\n 1855,\n/**/\n 1854,\n/**/\n 1853,\n/**/\n 1852,\n/**/\n 1851,\n/**/\n 1850,\n/**/\n 1849,\n/**/\n 1848,\n/**/\n 1847,\n/**/\n 1846,\n/**/\n 1845,\n/**/\n 1844,\n/**/\n 1843,\n/**/\n 1842,\n/**/\n 1841,\n/**/\n 1840,\n/**/\n 1839,\n/**/\n 1838,\n/**/\n 1837,\n/**/\n 1836,\n/**/\n 1835,\n/**/\n 1834,\n/**/\n 1833,\n/**/\n 1832,\n/**/\n 1831,\n/**/\n 1830,\n/**/\n 1829,\n/**/\n 1828,\n/**/\n 1827,\n/**/\n 1826,\n/**/\n 1825,\n/**/\n 1824,\n/**/\n 1823,\n/**/\n 1822,\n/**/\n 1821,\n/**/\n 1820,\n/**/\n 1819,\n/**/\n 1818,\n/**/\n 1817,\n/**/\n 1816,\n/**/\n 1815,\n/**/\n 1814,\n/**/\n 1813,\n/**/\n 1812,\n/**/\n 1811,\n/**/\n 1810,\n/**/\n 1809,\n/**/\n 1808,\n/**/\n 1807,\n/**/\n 1806,\n/**/\n 1805,\n/**/\n 1804,\n/**/\n 1803,\n/**/\n 1802,\n/**/\n 1801,\n/**/\n 1800,\n/**/\n 1799,\n/**/\n 1798,\n/**/\n 1797,\n/**/\n 1796,\n/**/\n 1795,\n/**/\n 1794,\n/**/\n 1793,\n/**/\n 1792,\n/**/\n 1791,\n/**/\n 1790,\n/**/\n 1789,\n/**/\n 1788,\n/**/\n 1787,\n/**/\n 1786,\n/**/\n 1785,\n/**/\n 1784,\n/**/\n 1783,\n/**/\n 1782,\n/**/\n 1781,\n/**/\n 1780,\n/**/\n 1779,\n/**/\n 1778,\n/**/\n 1777,\n/**/\n 1776,\n/**/\n 1775,\n/**/\n 1774,\n/**/\n 1773,\n/**/\n 1772,\n/**/\n 1771,\n/**/\n 1770,\n/**/\n 1769,\n/**/\n 1768,\n/**/\n 1767,\n/**/\n 1766,\n/**/\n 1765,\n/**/\n 1764,\n/**/\n 1763,\n/**/\n 1762,\n/**/\n 1761,\n/**/\n 1760,\n/**/\n 1759,\n/**/\n 1758,\n/**/\n 1757,\n/**/\n 1756,\n/**/\n 1755,\n/**/\n 1754,\n/**/\n 1753,\n/**/\n 1752,\n/**/\n 1751,\n/**/\n 1750,\n/**/\n 1749,\n/**/\n 1748,\n/**/\n 1747,\n/**/\n 1746,\n/**/\n 1745,\n/**/\n 1744,\n/**/\n 1743,\n/**/\n 1742,\n/**/\n 1741,\n/**/\n 1740,\n/**/\n 1739,\n/**/\n 1738,\n/**/\n 1737,\n/**/\n 1736,\n/**/\n 1735,\n/**/\n 1734,\n/**/\n 1733,\n/**/\n 1732,\n/**/\n 1731,\n/**/\n 1730,\n/**/\n 1729,\n/**/\n 1728,\n/**/\n 1727,\n/**/\n 1726,\n/**/\n 1725,\n/**/\n 1724,\n/**/\n 1723,\n/**/\n 1722,\n/**/\n 1721,\n/**/\n 1720,\n/**/\n 1719,\n/**/\n 1718,\n/**/\n 1717,\n/**/\n 1716,\n/**/\n 1715,\n/**/\n 1714,\n/**/\n 1713,\n/**/\n 1712,\n/**/\n 1711,\n/**/\n 1710,\n/**/\n 1709,\n/**/\n 1708,\n/**/\n 1707,\n/**/\n 1706,\n/**/\n 1705,\n/**/\n 1704,\n/**/\n 1703,\n/**/\n 1702,\n/**/\n 1701,\n/**/\n 1700,\n/**/\n 1699,\n/**/\n 1698,\n/**/\n 1697,\n/**/\n 1696,\n/**/\n 1695,\n/**/\n 1694,\n/**/\n 1693,\n/**/\n 1692,\n/**/\n 1691,\n/**/\n 1690,\n/**/\n 1689,\n/**/\n 1688,\n/**/\n 1687,\n/**/\n 1686,\n/**/\n 1685,\n/**/\n 1684,\n/**/\n 1683,\n/**/\n 1682,\n/**/\n 1681,\n/**/\n 1680,\n/**/\n 1679,\n/**/\n 1678,\n/**/\n 1677,\n/**/\n 1676,\n/**/\n 1675,\n/**/\n 1674,\n/**/\n 1673,\n/**/\n 1672,\n/**/\n 1671,\n/**/\n 1670,\n/**/\n 1669,\n/**/\n 1668,\n/**/\n 1667,\n/**/\n 1666,\n/**/\n 1665,\n/**/\n 1664,\n/**/\n 1663,\n/**/\n 1662,\n/**/\n 1661,\n/**/\n 1660,\n/**/\n 1659,\n/**/\n 1658,\n/**/\n 1657,\n/**/\n 1656,\n/**/\n 1655,\n/**/\n 1654,\n/**/\n 1653,\n/**/\n 1652,\n/**/\n 1651,\n/**/\n 1650,\n/**/\n 1649,\n/**/\n 1648,\n/**/\n 1647,\n/**/\n 1646,\n/**/\n 1645,\n/**/\n 1644,\n/**/\n 1643,\n/**/\n 1642,\n/**/\n 1641,\n/**/\n 1640,\n/**/\n 1639,\n/**/\n 1638,\n/**/\n 1637,\n/**/\n 1636,\n/**/\n 1635,\n/**/\n 1634,\n/**/\n 1633,\n/**/\n 1632,\n/**/\n 1631,\n/**/\n 1630,\n/**/\n 1629,\n/**/\n 1628,\n/**/\n 1627,\n/**/\n 1626,\n/**/\n 1625,\n/**/\n 1624,\n/**/\n 1623,\n/**/\n 1622,\n/**/\n 1621,\n/**/\n 1620,\n/**/\n 1619,\n/**/\n 1618,\n/**/\n 1617,\n/**/\n 1616,\n/**/\n 1615,\n/**/\n 1614,\n/**/\n 1613,\n/**/\n 1612,\n/**/\n 1611,\n/**/\n 1610,\n/**/\n 1609,\n/**/\n 1608,\n/**/\n 1607,\n/**/\n 1606,\n/**/\n 1605,\n/**/\n 1604,\n/**/\n 1603,\n/**/\n 1602,\n/**/\n 1601,\n/**/\n 1600,\n/**/\n 1599,\n/**/\n 1598,\n/**/\n 1597,\n/**/\n 1596,\n/**/\n 1595,\n/**/\n 1594,\n/**/\n 1593,\n/**/\n 1592,\n/**/\n 1591,\n/**/\n 1590,\n/**/\n 1589,\n/**/\n 1588,\n/**/\n 1587,\n/**/\n 1586,\n/**/\n 1585,\n/**/\n 1584,\n/**/\n 1583,\n/**/\n 1582,\n/**/\n 1581,\n/**/\n 1580,\n/**/\n 1579,\n/**/\n 1578,\n/**/\n 1577,\n/**/\n 1576,\n/**/\n 1575,\n/**/\n 1574,\n/**/\n 1573,\n/**/\n 1572,\n/**/\n 1571,\n/**/\n 1570,\n/**/\n 1569,\n/**/\n 1568,\n/**/\n 1567,\n/**/\n 1566,\n/**/\n 1565,\n/**/\n 1564,\n/**/\n 1563,\n/**/\n 1562,\n/**/\n 1561,\n/**/\n 1560,\n/**/\n 1559,\n/**/\n 1558,\n/**/\n 1557,\n/**/\n 1556,\n/**/\n 1555,\n/**/\n 1554,\n/**/\n 1553,\n/**/\n 1552,\n/**/\n 1551,\n/**/\n 1550,\n/**/\n 1549,\n/**/\n 1548,\n/**/\n 1547,\n/**/\n 1546,\n/**/\n 1545,\n/**/\n 1544,\n/**/\n 1543,\n/**/\n 1542,\n/**/\n 1541,\n/**/\n 1540,\n/**/\n 1539,\n/**/\n 1538,\n/**/\n 1537,\n/**/\n 1536,\n/**/\n 1535,\n/**/\n 1534,\n/**/\n 1533,\n/**/\n 1532,\n/**/\n 1531,\n/**/\n 1530,\n/**/\n 1529,\n/**/\n 1528,\n/**/\n 1527,\n/**/\n 1526,\n/**/\n 1525,\n/**/\n 1524,\n/**/\n 1523,\n/**/\n 1522,\n/**/\n 1521,\n/**/\n 1520,\n/**/\n 1519,\n/**/\n 1518,\n/**/\n 1517,\n/**/\n 1516,\n/**/\n 1515,\n/**/\n 1514,\n/**/\n 1513,\n/**/\n 1512,\n/**/\n 1511,\n/**/\n 1510,\n/**/\n 1509,\n/**/\n 1508,\n/**/\n 1507,\n/**/\n 1506,\n/**/\n 1505,\n/**/\n 1504,\n/**/\n 1503,\n/**/\n 1502,\n/**/\n 1501,\n/**/\n 1500,\n/**/\n 1499,\n/**/\n 1498,\n/**/\n 1497,\n/**/\n 1496,\n/**/\n 1495,\n/**/\n 1494,\n/**/\n 1493,\n/**/\n 1492,\n/**/\n 1491,\n/**/\n 1490,\n/**/\n 1489,\n/**/\n 1488,\n/**/\n 1487,\n/**/\n 1486,\n/**/\n 1485,\n/**/\n 1484,\n/**/\n 1483,\n/**/\n 1482,\n/**/\n 1481,\n/**/\n 1480,\n/**/\n 1479,\n/**/\n 1478,\n/**/\n 1477,\n/**/\n 1476,\n/**/\n 1475,\n/**/\n 1474,\n/**/\n 1473,\n/**/\n 1472,\n/**/\n 1471,\n/**/\n 1470,\n/**/\n 1469,\n/**/\n 1468,\n/**/\n 1467,\n/**/\n 1466,\n/**/\n 1465,\n/**/\n 1464,\n/**/\n 1463,\n/**/\n 1462,\n/**/\n 1461,\n/**/\n 1460,\n/**/\n 1459,\n/**/\n 1458,\n/**/\n 1457,\n/**/\n 1456,\n/**/\n 1455,\n/**/\n 1454,\n/**/\n 1453,\n/**/\n 1452,\n/**/\n 1451,\n/**/\n 1450,\n/**/\n 1449,\n/**/\n 1448,\n/**/\n 1447,\n/**/\n 1446,\n/**/\n 1445,\n/**/\n 1444,\n/**/\n 1443,\n/**/\n 1442,\n/**/\n 1441,\n/**/\n 1440,\n/**/\n 1439,\n/**/\n 1438,\n/**/\n 1437,\n/**/\n 1436,\n/**/\n 1435,\n/**/\n 1434,\n/**/\n 1433,\n/**/\n 1432,\n/**/\n 1431,\n/**/\n 1430,\n/**/\n 1429,\n/**/\n 1428,\n/**/\n 1427,\n/**/\n 1426,\n/**/\n 1425,\n/**/\n 1424,\n/**/\n 1423,\n/**/\n 1422,\n/**/\n 1421,\n/**/\n 1420,\n/**/\n 1419,\n/**/\n 1418,\n/**/\n 1417,\n/**/\n 1416,\n/**/\n 1415,\n/**/\n 1414,\n/**/\n 1413,\n/**/\n 1412,\n/**/\n 1411,\n/**/\n 1410,\n/**/\n 1409,\n/**/\n 1408,\n/**/\n 1407,\n/**/\n 1406,\n/**/\n 1405,\n/**/\n 1404,\n/**/\n 1403,\n/**/\n 1402,\n/**/\n 1401,\n/**/\n 1400,\n/**/\n 1399,\n/**/\n 1398,\n/**/\n 1397,\n/**/\n 1396,\n/**/\n 1395,\n/**/\n 1394,\n/**/\n 1393,\n/**/\n 1392,\n/**/\n 1391,\n/**/\n 1390,\n/**/\n 1389,\n/**/\n 1388,\n/**/\n 1387,\n/**/\n 1386,\n/**/\n 1385,\n/**/\n 1384,\n/**/\n 1383,\n/**/\n 1382,\n/**/\n 1381,\n/**/\n 1380,\n/**/\n 1379,\n/**/\n 1378,\n/**/\n 1377,\n/**/\n 1376,\n/**/\n 1375,\n/**/\n 1374,\n/**/\n 1373,\n/**/\n 1372,\n/**/\n 1371,\n/**/\n 1370,\n/**/\n 1369,\n/**/\n 1368,\n/**/\n 1367,\n/**/\n 1366,\n/**/\n 1365,\n/**/\n 1364,\n/**/\n 1363,\n/**/\n 1362,\n/**/\n 1361,\n/**/\n 1360,\n/**/\n 1359,\n/**/\n 1358,\n/**/\n 1357,\n/**/\n 1356,\n/**/\n 1355,\n/**/\n 1354,\n/**/\n 1353,\n/**/\n 1352,\n/**/\n 1351,\n/**/\n 1350,\n/**/\n 1349,\n/**/\n 1348,\n/**/\n 1347,\n/**/\n 1346,\n/**/\n 1345,\n/**/\n 1344,\n/**/\n 1343,\n/**/\n 1342,\n/**/\n 1341,\n/**/\n 1340,\n/**/\n 1339,\n/**/\n 1338,\n/**/\n 1337,\n/**/\n 1336,\n/**/\n 1335,\n/**/\n 1334,\n/**/\n 1333,\n/**/\n 1332,\n/**/\n 1331,\n/**/\n 1330,\n/**/\n 1329,\n/**/\n 1328,\n/**/\n 1327,\n/**/\n 1326,\n/**/\n 1325,\n/**/\n 1324,\n/**/\n 1323,\n/**/\n 1322,\n/**/\n 1321,\n/**/\n 1320,\n/**/\n 1319,\n/**/\n 1318,\n/**/\n 1317,\n/**/\n 1316,\n/**/\n 1315,\n/**/\n 1314,\n/**/\n 1313,\n/**/\n 1312,\n/**/\n 1311,\n/**/\n 1310,\n/**/\n 1309,\n/**/\n 1308,\n/**/\n 1307,\n/**/\n 1306,\n/**/\n 1305,\n/**/\n 1304,\n/**/\n 1303,\n/**/\n 1302,\n/**/\n 1301,\n/**/\n 1300,\n/**/\n 1299,\n/**/\n 1298,\n/**/\n 1297,\n/**/\n 1296,\n/**/\n 1295,\n/**/\n 1294,\n/**/\n 1293,\n/**/\n 1292,\n/**/\n 1291,\n/**/\n 1290,\n/**/\n 1289,\n/**/\n 1288,\n/**/\n 1287,\n/**/\n 1286,\n/**/\n 1285,\n/**/\n 1284,\n/**/\n 1283,\n/**/\n 1282,\n/**/\n 1281,\n/**/\n 1280,\n/**/\n 1279,\n/**/\n 1278,\n/**/\n 1277,\n/**/\n 1276,\n/**/\n 1275,\n/**/\n 1274,\n/**/\n 1273,\n/**/\n 1272,\n/**/\n 1271,\n/**/\n 1270,\n/**/\n 1269,\n/**/\n 1268,\n/**/\n 1267,\n/**/\n 1266,\n/**/\n 1265,\n/**/\n 1264,\n/**/\n 1263,\n/**/\n 1262,\n/**/\n 1261,\n/**/\n 1260,\n/**/\n 1259,\n/**/\n 1258,\n/**/\n 1257,\n/**/\n 1256,\n/**/\n 1255,\n/**/\n 1254,\n/**/\n 1253,\n/**/\n 1252,\n/**/\n 1251,\n/**/\n 1250,\n/**/\n 1249,\n/**/\n 1248,\n/**/\n 1247,\n/**/\n 1246,\n/**/\n 1245,\n/**/\n 1244,\n/**/\n 1243,\n/**/\n 1242,\n/**/\n 1241,\n/**/\n 1240,\n/**/\n 1239,\n/**/\n 1238,\n/**/\n 1237,\n/**/\n 1236,\n/**/\n 1235,\n/**/\n 1234,\n/**/\n 1233,\n/**/\n 1232,\n/**/\n 1231,\n/**/\n 1230,\n/**/\n 1229,\n/**/\n 1228,\n/**/\n 1227,\n/**/\n 1226,\n/**/\n 1225,\n/**/\n 1224,\n/**/\n 1223,\n/**/\n 1222,\n/**/\n 1221,\n/**/\n 1220,\n/**/\n 1219,\n/**/\n 1218,\n/**/\n 1217,\n/**/\n 1216,\n/**/\n 1215,\n/**/\n 1214,\n/**/\n 1213,\n/**/\n 1212,\n/**/\n 1211,\n/**/\n 1210,\n/**/\n 1209,\n/**/\n 1208,\n/**/\n 1207,\n/**/\n 1206,\n/**/\n 1205,\n/**/\n 1204,\n/**/\n 1203,\n/**/\n 1202,\n/**/\n 1201,\n/**/\n 1200,\n/**/\n 1199,\n/**/\n 1198,\n/**/\n 1197,\n/**/\n 1196,\n/**/\n 1195,\n/**/\n 1194,\n/**/\n 1193,\n/**/\n 1192,\n/**/\n 1191,\n/**/\n 1190,\n/**/\n 1189,\n/**/\n 1188,\n/**/\n 1187,\n/**/\n 1186,\n/**/\n 1185,\n/**/\n 1184,\n/**/\n 1183,\n/**/\n 1182,\n/**/\n 1181,\n/**/\n 1180,\n/**/\n 1179,\n/**/\n 1178,\n/**/\n 1177,\n/**/\n 1176,\n/**/\n 1175,\n/**/\n 1174,\n/**/\n 1173,\n/**/\n 1172,\n/**/\n 1171,\n/**/\n 1170,\n/**/\n 1169,\n/**/\n 1168,\n/**/\n 1167,\n/**/\n 1166,\n/**/\n 1165,\n/**/\n 1164,\n/**/\n 1163,\n/**/\n 1162,\n/**/\n 1161,\n/**/\n 1160,\n/**/\n 1159,\n/**/\n 1158,\n/**/\n 1157,\n/**/\n 1156,\n/**/\n 1155,\n/**/\n 1154,\n/**/\n 1153,\n/**/\n 1152,\n/**/\n 1151,\n/**/\n 1150,\n/**/\n 1149,\n/**/\n 1148,\n/**/\n 1147,\n/**/\n 1146,\n/**/\n 1145,\n/**/\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 while (l < h)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\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 version8<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": [2081, 87, 736], "buggy_code_start_loc": [2079, 1, 736], "filenames": ["src/indent.c", "src/testdir/test_lispwords.vim", "src/version.c"], "fixing_code_end_loc": [2084, 98, 739], "fixing_code_start_loc": [2079, 1, 737], "message": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "C88D3533-C1C8-4615-A2D5-30AC85BA943B", "versionEndExcluding": "8.2.5151", "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}, {"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": "Out-of-bounds Read in GitHub repository vim/vim prior to 8.2."}, {"lang": "es", "value": "Una Lectura Fuera de L\u00edmites en el repositorio de GitHub vim/vim versiones anteriores a 8.2"}], "evaluatorComment": null, "id": "CVE-2022-2183", "lastModified": "2023-05-03T12:15:46.177", "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-06-23T19:15:08.577", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/d74ca3f9-380d-4c0a-b61c-11113cc98975"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GFD2A4YLBR7OIRHTL7CK6YNMEIQ264CN/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/U743FMJGFQ35GBPCQ6OWMVZEJPDFVEWM/"}, {"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-125"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/8eba2bd291b347e3008aa9e565652d51ad638cfa"}, "type": "CWE-125"}
| 319
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * File System Virtual Channel\n *\n * Copyright 2010-2011 Vic Lee\n * Copyright 2010-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */",
"#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif",
"#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>",
"#include <winpr/crt.h>\n#include <winpr/path.h>\n#include <winpr/file.h>\n#include <winpr/string.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/stream.h>\n#include <winpr/environment.h>\n#include <winpr/interlocked.h>\n#include <winpr/collections.h>\n#include <winpr/shell.h>",
"#include <freerdp/channels/rdpdr.h>",
"#include \"drive_file.h\"",
"typedef struct _DRIVE_DEVICE DRIVE_DEVICE;",
"struct _DRIVE_DEVICE\n{\n\tDEVICE device;",
"\tWCHAR* path;\n\tBOOL automount;\n\tUINT32 PathLength;\n\twListDictionary* files;",
"\tHANDLE thread;\n\twMessageQueue* IrpQueue;",
"\tDEVMAN* devman;",
"\trdpContext* rdpcontext;\n};",
"static UINT sys_code_page = 0;",
"static DWORD drive_map_windows_err(DWORD fs_errno)\n{\n\tDWORD rc;",
"\t/* try to return NTSTATUS version of error code */",
"\tswitch (fs_errno)\n\t{\n\t\tcase STATUS_SUCCESS:\n\t\t\trc = STATUS_SUCCESS;\n\t\t\tbreak;",
"\t\tcase ERROR_ACCESS_DENIED:\n\t\tcase ERROR_SHARING_VIOLATION:\n\t\t\trc = STATUS_ACCESS_DENIED;\n\t\t\tbreak;",
"\t\tcase ERROR_FILE_NOT_FOUND:\n\t\t\trc = STATUS_NO_SUCH_FILE;\n\t\t\tbreak;",
"\t\tcase ERROR_BUSY_DRIVE:\n\t\t\trc = STATUS_DEVICE_BUSY;\n\t\t\tbreak;",
"\t\tcase ERROR_INVALID_DRIVE:\n\t\t\trc = STATUS_NO_SUCH_DEVICE;\n\t\t\tbreak;",
"\t\tcase ERROR_NOT_READY:\n\t\t\trc = STATUS_NO_SUCH_DEVICE;\n\t\t\tbreak;",
"\t\tcase ERROR_FILE_EXISTS:\n\t\tcase ERROR_ALREADY_EXISTS:\n\t\t\trc = STATUS_OBJECT_NAME_COLLISION;\n\t\t\tbreak;",
"\t\tcase ERROR_INVALID_NAME:\n\t\t\trc = STATUS_NO_SUCH_FILE;\n\t\t\tbreak;",
"\t\tcase ERROR_INVALID_HANDLE:\n\t\t\trc = STATUS_INVALID_HANDLE;\n\t\t\tbreak;",
"\t\tcase ERROR_NO_MORE_FILES:\n\t\t\trc = STATUS_NO_MORE_FILES;\n\t\t\tbreak;",
"\t\tcase ERROR_DIRECTORY:\n\t\t\trc = STATUS_NOT_A_DIRECTORY;\n\t\t\tbreak;",
"\t\tcase ERROR_PATH_NOT_FOUND:\n\t\t\trc = STATUS_OBJECT_PATH_NOT_FOUND;\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\trc = STATUS_UNSUCCESSFUL;\n\t\t\tWLog_ERR(TAG, \"Error code not found: %\" PRIu32 \"\", fs_errno);\n\t\t\tbreak;\n\t}",
"\treturn rc;\n}",
"static DRIVE_FILE* drive_get_file_by_id(DRIVE_DEVICE* drive, UINT32 id)\n{\n\tDRIVE_FILE* file = NULL;\n\tvoid* key = (void*)(size_t)id;",
"\tif (!drive)\n\t\treturn NULL;",
"\tfile = (DRIVE_FILE*)ListDictionary_GetItemValue(drive->files, key);\n\treturn file;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_create(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT32 FileId;\n\tDRIVE_FILE* file;\n\tBYTE Information;\n\tUINT32 FileAttributes;\n\tUINT32 SharedAccess;\n\tUINT32 DesiredAccess;\n\tUINT32 CreateDisposition;\n\tUINT32 CreateOptions;\n\tUINT32 PathLength;\n\tUINT64 allocationSize;\n\tconst WCHAR* path;",
"\tif (!drive || !irp || !irp->devman || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 6 * 4 + 8)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, DesiredAccess);\n\tStream_Read_UINT64(irp->input, allocationSize);\n\tStream_Read_UINT32(irp->input, FileAttributes);\n\tStream_Read_UINT32(irp->input, SharedAccess);\n\tStream_Read_UINT32(irp->input, CreateDisposition);\n\tStream_Read_UINT32(irp->input, CreateOptions);\n\tStream_Read_UINT32(irp->input, PathLength);",
"\tif (Stream_GetRemainingLength(irp->input) < PathLength)\n\t\treturn ERROR_INVALID_DATA;",
"\tpath = (const WCHAR*)Stream_Pointer(irp->input);\n\tFileId = irp->devman->id_sequence++;\n\tfile = drive_file_new(drive->path, path, PathLength, FileId, DesiredAccess, CreateDisposition,\n\t CreateOptions, FileAttributes, SharedAccess);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tFileId = 0;\n\t\tInformation = 0;\n\t}\n\telse\n\t{\n\t\tvoid* key = (void*)(size_t)file->id;",
"\t\tif (!ListDictionary_Add(drive->files, key, file))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_Add failed!\");\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}",
"\t\tswitch (CreateDisposition)\n\t\t{\n\t\t\tcase FILE_SUPERSEDE:\n\t\t\tcase FILE_OPEN:\n\t\t\tcase FILE_CREATE:\n\t\t\tcase FILE_OVERWRITE:\n\t\t\t\tInformation = FILE_SUPERSEDED;\n\t\t\t\tbreak;",
"\t\t\tcase FILE_OPEN_IF:\n\t\t\t\tInformation = FILE_OPENED;\n\t\t\t\tbreak;",
"\t\t\tcase FILE_OVERWRITE_IF:\n\t\t\t\tInformation = FILE_OVERWRITTEN;\n\t\t\t\tbreak;",
"\t\t\tdefault:\n\t\t\t\tInformation = 0;\n\t\t\t\tbreak;\n\t\t}\n\t}",
"\tStream_Write_UINT32(irp->output, FileId);\n\tStream_Write_UINT8(irp->output, Information);\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_close(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tvoid* key;\n\tDRIVE_FILE* file;",
"\tif (!drive || !irp || !irp->Complete || !irp->output)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tfile = drive_get_file_by_id(drive, irp->FileId);\n\tkey = (void*)(size_t)irp->FileId;",
"\tif (!file)\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\telse\n\t{\n\t\tListDictionary_Remove(drive->files, key);",
"\t\tif (drive_file_free(file))\n\t\t\tirp->IoStatus = STATUS_SUCCESS;\n\t\telse\n\t\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\tStream_Zero(irp->output, 5); /* Padding(5) */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_read(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 Length;\n\tUINT64 Offset;",
"\tif (!drive || !irp || !irp->output || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 12)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, Length);\n\tStream_Read_UINT64(irp->input, Offset);\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tLength = 0;\n\t}\n\telse if (!drive_file_seek(file, Offset))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tLength = 0;\n\t}",
"\tif (!Stream_EnsureRemainingCapacity(irp->output, Length + 4))\n\t{\n\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\treturn ERROR_INTERNAL_ERROR;\n\t}\n\telse if (Length == 0)\n\t\tStream_Write_UINT32(irp->output, 0);\n\telse\n\t{\n\t\tBYTE* buffer = Stream_Pointer(irp->output) + sizeof(UINT32);",
"\t\tif (!drive_file_read(file, buffer, &Length))\n\t\t{\n\t\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\t\tStream_Write_UINT32(irp->output, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStream_Write_UINT32(irp->output, Length);\n\t\t\tStream_Seek(irp->output, Length);\n\t\t}\n\t}",
"\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_write(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 Length;\n\tUINT64 Offset;",
"",
"\n\tif (!drive || !irp || !irp->input || !irp->output || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, Length);\n\tStream_Read_UINT64(irp->input, Offset);\n\tStream_Seek(irp->input, 20); /* Padding */",
"",
"\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tLength = 0;\n\t}\n\telse if (!drive_file_seek(file, Offset))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tLength = 0;\n\t}",
"\telse if (!drive_file_write(file, Stream_Pointer(irp->input), Length))",
"\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tLength = 0;\n\t}",
"\tStream_Write_UINT32(irp->output, Length);\n\tStream_Write_UINT8(irp->output, 0); /* Padding */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_query_information(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 FsInformationClass;",
"\tif (!drive || !irp || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t}\n\telse if (!drive_file_query_information(file, FsInformationClass, irp->output))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_set_information(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 FsInformationClass;\n\tUINT32 Length;",
"\tif (!drive || !irp || !irp->Complete || !irp->input || !irp->output)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tStream_Read_UINT32(irp->input, Length);\n\tStream_Seek(irp->input, 24); /* Padding */\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t}\n\telse if (!drive_file_set_information(file, FsInformationClass, Length, irp->input))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\tif (file && file->is_dir && !PathIsDirectoryEmptyW(file->fullpath))\n\t\tirp->IoStatus = STATUS_DIRECTORY_NOT_EMPTY;",
"\tStream_Write_UINT32(irp->output, Length);\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_query_volume_information(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT32 FsInformationClass;\n\twStream* output = NULL;\n\tchar* volumeLabel = { \"FREERDP\" };\n\tchar* diskType = { \"FAT32\" };\n\tWCHAR* outStr = NULL;\n\tint length;\n\tDWORD lpSectorsPerCluster;\n\tDWORD lpBytesPerSector;\n\tDWORD lpNumberOfFreeClusters;\n\tDWORD lpTotalNumberOfClusters;\n\tWIN32_FILE_ATTRIBUTE_DATA wfad;",
"\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\toutput = irp->output;",
"\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tGetDiskFreeSpaceW(drive->path, &lpSectorsPerCluster, &lpBytesPerSector, &lpNumberOfFreeClusters,\n\t &lpTotalNumberOfClusters);",
"\tswitch (FsInformationClass)\n\t{\n\t\tcase FileFsVolumeInformation:",
"\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232108.aspx */\n\t\t\tif ((length = ConvertToUnicode(sys_code_page, 0, volumeLabel, -1, &outStr, 0) * 2) <= 0)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"ConvertToUnicode failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, 17 + length); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 17 + length))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\tfree(outStr);\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tGetFileAttributesExW(drive->path, GetFileExInfoStandard, &wfad);\n\t\t\tStream_Write_UINT32(output, wfad.ftCreationTime.dwLowDateTime); /* VolumeCreationTime */\n\t\t\tStream_Write_UINT32(output,\n\t\t\t wfad.ftCreationTime.dwHighDateTime); /* VolumeCreationTime */\n\t\t\tStream_Write_UINT32(output, lpNumberOfFreeClusters & 0xffff); /* VolumeSerialNumber */\n\t\t\tStream_Write_UINT32(output, length); /* VolumeLabelLength */\n\t\t\tStream_Write_UINT8(output, 0); /* SupportsObjects */\n\t\t\t/* Reserved(1), MUST NOT be added! */\n\t\t\tStream_Write(output, outStr, length); /* VolumeLabel (Unicode) */\n\t\t\tfree(outStr);\n\t\t\tbreak;",
"\t\tcase FileFsSizeInformation:\n\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232107.aspx */\n\t\t\tStream_Write_UINT32(output, 24); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 24))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */\n\t\t\tStream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */\n\t\t\tStream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */\n\t\t\tStream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */\n\t\t\tbreak;",
"\t\tcase FileFsAttributeInformation:",
"\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232101.aspx */\n\t\t\tif ((length = ConvertToUnicode(sys_code_page, 0, diskType, -1, &outStr, 0) * 2) <= 0)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"ConvertToUnicode failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, 12 + length); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 12 + length))\n\t\t\t{\n\t\t\t\tfree(outStr);\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES |\n\t\t\t FILE_UNICODE_ON_DISK); /* FileSystemAttributes */\n\t\t\tStream_Write_UINT32(output, MAX_PATH); /* MaximumComponentNameLength */\n\t\t\tStream_Write_UINT32(output, length); /* FileSystemNameLength */\n\t\t\tStream_Write(output, outStr, length); /* FileSystemName (Unicode) */\n\t\t\tfree(outStr);\n\t\t\tbreak;",
"\t\tcase FileFsFullSizeInformation:\n\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232104.aspx */\n\t\t\tStream_Write_UINT32(output, 32); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 32))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */\n\t\t\tStream_Write_UINT64(output,\n\t\t\t lpNumberOfFreeClusters); /* CallerAvailableAllocationUnits */\n\t\t\tStream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */\n\t\t\tStream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */\n\t\t\tStream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */\n\t\t\tbreak;",
"\t\tcase FileFsDeviceInformation:\n\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232109.aspx */\n\t\t\tStream_Write_UINT32(output, 8); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 8))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, FILE_DEVICE_DISK); /* DeviceType */\n\t\t\tStream_Write_UINT32(output, 0); /* Characteristics */\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\t\tStream_Write_UINT32(output, 0); /* Length */\n\t\t\tbreak;\n\t}",
"\treturn irp->Complete(irp);\n}",
"/* http://msdn.microsoft.com/en-us/library/cc241518.aspx */",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_silent_ignore(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT32 FsInformationClass;",
"\tif (!drive || !irp || !irp->output || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tStream_Write_UINT32(irp->output, 0); /* Length */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_query_directory(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tconst WCHAR* path;\n\tDRIVE_FILE* file;\n\tBYTE InitialQuery;\n\tUINT32 PathLength;\n\tUINT32 FsInformationClass;",
"\tif (!drive || !irp || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tStream_Read_UINT8(irp->input, InitialQuery);\n\tStream_Read_UINT32(irp->input, PathLength);\n\tStream_Seek(irp->input, 23); /* Padding */\n\tpath = (WCHAR*)Stream_Pointer(irp->input);\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (file == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tStream_Write_UINT32(irp->output, 0); /* Length */\n\t}\n\telse if (!drive_file_query_directory(file, FsInformationClass, InitialQuery, path, PathLength,\n\t irp->output))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_directory_control(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tswitch (irp->MinorFunction)\n\t{\n\t\tcase IRP_MN_QUERY_DIRECTORY:\n\t\t\treturn drive_process_irp_query_directory(drive, irp);",
"\t\tcase IRP_MN_NOTIFY_CHANGE_DIRECTORY: /* TODO */\n\t\t\treturn irp->Discard(irp);",
"\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\tStream_Write_UINT32(irp->output, 0); /* Length */\n\t\t\treturn irp->Complete(irp);\n\t}",
"\treturn CHANNEL_RC_OK;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_device_control(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tStream_Write_UINT32(irp->output, 0); /* OutputBufferLength */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT error;",
"\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tirp->IoStatus = STATUS_SUCCESS;",
"\tswitch (irp->MajorFunction)\n\t{\n\t\tcase IRP_MJ_CREATE:\n\t\t\terror = drive_process_irp_create(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_CLOSE:\n\t\t\terror = drive_process_irp_close(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_READ:\n\t\t\terror = drive_process_irp_read(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_WRITE:\n\t\t\terror = drive_process_irp_write(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_QUERY_INFORMATION:\n\t\t\terror = drive_process_irp_query_information(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_SET_INFORMATION:\n\t\t\terror = drive_process_irp_set_information(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_QUERY_VOLUME_INFORMATION:\n\t\t\terror = drive_process_irp_query_volume_information(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_LOCK_CONTROL:\n\t\t\terror = drive_process_irp_silent_ignore(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_DIRECTORY_CONTROL:\n\t\t\terror = drive_process_irp_directory_control(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\terror = drive_process_irp_device_control(drive, irp);\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\terror = irp->Complete(irp);\n\t\t\tbreak;\n\t}",
"\treturn error;\n}",
"static DWORD WINAPI drive_thread_func(LPVOID arg)\n{\n\tIRP* irp;\n\twMessage message;\n\tDRIVE_DEVICE* drive = (DRIVE_DEVICE*)arg;\n\tUINT error = CHANNEL_RC_OK;",
"\tif (!drive)\n\t{\n\t\terror = ERROR_INVALID_PARAMETER;\n\t\tgoto fail;\n\t}",
"\twhile (1)\n\t{\n\t\tif (!MessageQueue_Wait(drive->IrpQueue))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Wait failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}",
"\t\tif (!MessageQueue_Peek(drive->IrpQueue, &message, TRUE))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Peek failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}",
"\t\tif (message.id == WMQ_QUIT)\n\t\t\tbreak;",
"\t\tirp = (IRP*)message.wParam;",
"\t\tif (irp)\n\t\t{\n\t\t\tif ((error = drive_process_irp(drive, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"drive_process_irp failed with error %\" PRIu32 \"!\", error);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"fail:",
"\tif (error && drive && drive->rdpcontext)\n\t\tsetChannelError(drive->rdpcontext, error, \"drive_thread_func reported an error\");",
"\tExitThread(error);\n\treturn error;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_irp_request(DEVICE* device, IRP* irp)\n{\n\tDRIVE_DEVICE* drive = (DRIVE_DEVICE*)device;",
"\tif (!drive)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (!MessageQueue_Post(drive->IrpQueue, NULL, 0, (void*)irp, NULL))\n\t{\n\t\tWLog_ERR(TAG, \"MessageQueue_Post failed!\");\n\t\treturn ERROR_INTERNAL_ERROR;\n\t}",
"\treturn CHANNEL_RC_OK;\n}",
"static UINT drive_free_int(DRIVE_DEVICE* drive)\n{\n\tUINT error = CHANNEL_RC_OK;",
"\tif (!drive)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tCloseHandle(drive->thread);\n\tListDictionary_Free(drive->files);\n\tMessageQueue_Free(drive->IrpQueue);\n\tStream_Free(drive->device.data, TRUE);\n\tfree(drive->path);\n\tfree(drive);\n\treturn error;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_free(DEVICE* device)\n{\n\tDRIVE_DEVICE* drive = (DRIVE_DEVICE*)device;\n\tUINT error = CHANNEL_RC_OK;",
"\tif (!drive)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (MessageQueue_PostQuit(drive->IrpQueue, 0) &&\n\t (WaitForSingleObject(drive->thread, INFINITE) == WAIT_FAILED))\n\t{\n\t\terror = GetLastError();\n\t\tWLog_ERR(TAG, \"WaitForSingleObject failed with error %\" PRIu32 \"\", error);\n\t\treturn error;\n\t}",
"\treturn drive_free_int(drive);\n}",
"/**\n * Helper function used for freeing list dictionary value object\n */\nstatic void drive_file_objfree(void* obj)\n{\n\tdrive_file_free((DRIVE_FILE*)obj);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_register_drive_path(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, const char* name,\n const char* path, BOOL automount)\n{\n\tsize_t i, length;\n\tDRIVE_DEVICE* drive;\n\tUINT error = ERROR_INTERNAL_ERROR;",
"\tif (!pEntryPoints || !name || !path)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Invalid parameters: pEntryPoints=%p, name=%p, path=%p\", pEntryPoints,\n\t\t name, path);\n\t\treturn ERROR_INVALID_PARAMETER;\n\t}",
"\tif (name[0] && path[0])\n\t{\n\t\tsize_t pathLength = strnlen(path, MAX_PATH);\n\t\tdrive = (DRIVE_DEVICE*)calloc(1, sizeof(DRIVE_DEVICE));",
"\t\tif (!drive)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}",
"\t\tdrive->device.type = RDPDR_DTYP_FILESYSTEM;\n\t\tdrive->device.IRPRequest = drive_irp_request;\n\t\tdrive->device.Free = drive_free;\n\t\tdrive->rdpcontext = pEntryPoints->rdpcontext;\n\t\tdrive->automount = automount;\n\t\tlength = strlen(name);\n\t\tdrive->device.data = Stream_New(NULL, length + 1);",
"\t\tif (!drive->device.data)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tfor (i = 0; i < length; i++)\n\t\t{\n\t\t\t/* Filter 2.2.1.3 Device Announce Header (DEVICE_ANNOUNCE) forbidden symbols */\n\t\t\tswitch (name[i])\n\t\t\t{\n\t\t\t\tcase ':':\n\t\t\t\tcase '<':\n\t\t\t\tcase '>':\n\t\t\t\tcase '\\\"':\n\t\t\t\tcase '/':\n\t\t\t\tcase '\\\\':\n\t\t\t\tcase '|':\n\t\t\t\tcase ' ':\n\t\t\t\t\tStream_Write_UINT8(drive->device.data, '_');\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tStream_Write_UINT8(drive->device.data, (BYTE)name[i]);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tStream_Write_UINT8(drive->device.data, '\\0');",
"\t\tdrive->device.name = (const char*)Stream_Buffer(drive->device.data);\n\t\tif (!drive->device.name)\n\t\t\tgoto out_error;",
"\t\tif ((pathLength > 1) && (path[pathLength - 1] == '/'))\n\t\t\tpathLength--;",
"\t\tif (ConvertToUnicode(sys_code_page, 0, path, pathLength, &drive->path, 0) <= 0)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ConvertToUnicode failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tdrive->files = ListDictionary_New(TRUE);",
"\t\tif (!drive->files)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tListDictionary_ValueObject(drive->files)->fnObjectFree = drive_file_objfree;\n\t\tdrive->IrpQueue = MessageQueue_New(NULL);",
"\t\tif (!drive->IrpQueue)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tif ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)drive)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"RegisterDevice failed with error %\" PRIu32 \"!\", error);\n\t\t\tgoto out_error;\n\t\t}",
"\t\tif (!(drive->thread =\n\t\t CreateThread(NULL, 0, drive_thread_func, drive, CREATE_SUSPENDED, NULL)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"CreateThread failed!\");\n\t\t\tgoto out_error;\n\t\t}",
"\t\tResumeThread(drive->thread);\n\t}",
"\treturn CHANNEL_RC_OK;\nout_error:\n\tdrive_free_int(drive);\n\treturn error;\n}",
"#ifdef BUILTIN_CHANNELS\n#define DeviceServiceEntry drive_DeviceServiceEntry\n#else\n#define DeviceServiceEntry FREERDP_API DeviceServiceEntry\n#endif",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)\n{\n\tRDPDR_DRIVE* drive;\n\tUINT error;\n#ifdef WIN32\n\tchar* dev;\n\tint len;\n\tchar devlist[512], buf[512];\n\tchar* bufdup;\n\tchar* devdup;\n#endif\n\tdrive = (RDPDR_DRIVE*)pEntryPoints->device;\n#ifndef WIN32\n\tsys_code_page = CP_UTF8;",
"\tif (strcmp(drive->Path, \"*\") == 0)\n\t{\n\t\t/* all drives */\n\t\tfree(drive->Path);\n\t\tdrive->Path = _strdup(\"/\");",
"\t\tif (!drive->Path)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\t}\n\telse if (strcmp(drive->Path, \"%\") == 0)\n\t{\n\t\tfree(drive->Path);\n\t\tdrive->Path = GetKnownPath(KNOWN_PATH_HOME);",
"\t\tif (!drive->Path)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\t}",
"\terror = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);\n#else\n\tsys_code_page = GetACP();",
"\t/* Special case: path[0] == '*' -> export all drives */\n\t/* Special case: path[0] == '%' -> user home dir */\n\tif (strcmp(drive->Path, \"%\") == 0)\n\t{\n\t\tGetEnvironmentVariableA(\"USERPROFILE\", buf, sizeof(buf));\n\t\tPathCchAddBackslashA(buf, sizeof(buf));\n\t\tfree(drive->Path);\n\t\tdrive->Path = _strdup(buf);",
"\t\tif (!drive->Path)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}",
"\t\terror = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);\n\t}\n\telse if (strcmp(drive->Path, \"*\") == 0)\n\t{\n\t\tint i;\n\t\t/* Enumerate all devices: */\n\t\tGetLogicalDriveStringsA(sizeof(devlist) - 1, devlist);",
"\t\tfor (dev = devlist, i = 0; *dev; dev += 4, i++)\n\t\t{\n\t\t\tif (*dev > 'B')\n\t\t\t{\n\t\t\t\t/* Suppress disk drives A and B to avoid pesty messages */\n\t\t\t\tlen = sprintf_s(buf, sizeof(buf) - 4, \"%s\", drive->Name);\n\t\t\t\tbuf[len] = '_';\n\t\t\t\tbuf[len + 1] = dev[0];\n\t\t\t\tbuf[len + 2] = 0;\n\t\t\t\tbuf[len + 3] = 0;",
"\t\t\t\tif (!(bufdup = _strdup(buf)))\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t\t}",
"\t\t\t\tif (!(devdup = _strdup(dev)))\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t\t}",
"\t\t\t\tif ((error = drive_register_drive_path(pEntryPoints, bufdup, devdup, TRUE)))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\terror = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);\n\t}",
"#endif\n\treturn error;\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,
0,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
| 320
|
Determine whether the {function_name} code is vulnerable or not.
|
[
"/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * File System Virtual Channel\n *\n * Copyright 2010-2011 Vic Lee\n * Copyright 2010-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */",
"#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif",
"#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>",
"#include <winpr/crt.h>\n#include <winpr/path.h>\n#include <winpr/file.h>\n#include <winpr/string.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/stream.h>\n#include <winpr/environment.h>\n#include <winpr/interlocked.h>\n#include <winpr/collections.h>\n#include <winpr/shell.h>",
"#include <freerdp/channels/rdpdr.h>",
"#include \"drive_file.h\"",
"typedef struct _DRIVE_DEVICE DRIVE_DEVICE;",
"struct _DRIVE_DEVICE\n{\n\tDEVICE device;",
"\tWCHAR* path;\n\tBOOL automount;\n\tUINT32 PathLength;\n\twListDictionary* files;",
"\tHANDLE thread;\n\twMessageQueue* IrpQueue;",
"\tDEVMAN* devman;",
"\trdpContext* rdpcontext;\n};",
"static UINT sys_code_page = 0;",
"static DWORD drive_map_windows_err(DWORD fs_errno)\n{\n\tDWORD rc;",
"\t/* try to return NTSTATUS version of error code */",
"\tswitch (fs_errno)\n\t{\n\t\tcase STATUS_SUCCESS:\n\t\t\trc = STATUS_SUCCESS;\n\t\t\tbreak;",
"\t\tcase ERROR_ACCESS_DENIED:\n\t\tcase ERROR_SHARING_VIOLATION:\n\t\t\trc = STATUS_ACCESS_DENIED;\n\t\t\tbreak;",
"\t\tcase ERROR_FILE_NOT_FOUND:\n\t\t\trc = STATUS_NO_SUCH_FILE;\n\t\t\tbreak;",
"\t\tcase ERROR_BUSY_DRIVE:\n\t\t\trc = STATUS_DEVICE_BUSY;\n\t\t\tbreak;",
"\t\tcase ERROR_INVALID_DRIVE:\n\t\t\trc = STATUS_NO_SUCH_DEVICE;\n\t\t\tbreak;",
"\t\tcase ERROR_NOT_READY:\n\t\t\trc = STATUS_NO_SUCH_DEVICE;\n\t\t\tbreak;",
"\t\tcase ERROR_FILE_EXISTS:\n\t\tcase ERROR_ALREADY_EXISTS:\n\t\t\trc = STATUS_OBJECT_NAME_COLLISION;\n\t\t\tbreak;",
"\t\tcase ERROR_INVALID_NAME:\n\t\t\trc = STATUS_NO_SUCH_FILE;\n\t\t\tbreak;",
"\t\tcase ERROR_INVALID_HANDLE:\n\t\t\trc = STATUS_INVALID_HANDLE;\n\t\t\tbreak;",
"\t\tcase ERROR_NO_MORE_FILES:\n\t\t\trc = STATUS_NO_MORE_FILES;\n\t\t\tbreak;",
"\t\tcase ERROR_DIRECTORY:\n\t\t\trc = STATUS_NOT_A_DIRECTORY;\n\t\t\tbreak;",
"\t\tcase ERROR_PATH_NOT_FOUND:\n\t\t\trc = STATUS_OBJECT_PATH_NOT_FOUND;\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\trc = STATUS_UNSUCCESSFUL;\n\t\t\tWLog_ERR(TAG, \"Error code not found: %\" PRIu32 \"\", fs_errno);\n\t\t\tbreak;\n\t}",
"\treturn rc;\n}",
"static DRIVE_FILE* drive_get_file_by_id(DRIVE_DEVICE* drive, UINT32 id)\n{\n\tDRIVE_FILE* file = NULL;\n\tvoid* key = (void*)(size_t)id;",
"\tif (!drive)\n\t\treturn NULL;",
"\tfile = (DRIVE_FILE*)ListDictionary_GetItemValue(drive->files, key);\n\treturn file;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_create(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT32 FileId;\n\tDRIVE_FILE* file;\n\tBYTE Information;\n\tUINT32 FileAttributes;\n\tUINT32 SharedAccess;\n\tUINT32 DesiredAccess;\n\tUINT32 CreateDisposition;\n\tUINT32 CreateOptions;\n\tUINT32 PathLength;\n\tUINT64 allocationSize;\n\tconst WCHAR* path;",
"\tif (!drive || !irp || !irp->devman || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 6 * 4 + 8)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, DesiredAccess);\n\tStream_Read_UINT64(irp->input, allocationSize);\n\tStream_Read_UINT32(irp->input, FileAttributes);\n\tStream_Read_UINT32(irp->input, SharedAccess);\n\tStream_Read_UINT32(irp->input, CreateDisposition);\n\tStream_Read_UINT32(irp->input, CreateOptions);\n\tStream_Read_UINT32(irp->input, PathLength);",
"\tif (Stream_GetRemainingLength(irp->input) < PathLength)\n\t\treturn ERROR_INVALID_DATA;",
"\tpath = (const WCHAR*)Stream_Pointer(irp->input);\n\tFileId = irp->devman->id_sequence++;\n\tfile = drive_file_new(drive->path, path, PathLength, FileId, DesiredAccess, CreateDisposition,\n\t CreateOptions, FileAttributes, SharedAccess);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tFileId = 0;\n\t\tInformation = 0;\n\t}\n\telse\n\t{\n\t\tvoid* key = (void*)(size_t)file->id;",
"\t\tif (!ListDictionary_Add(drive->files, key, file))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_Add failed!\");\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}",
"\t\tswitch (CreateDisposition)\n\t\t{\n\t\t\tcase FILE_SUPERSEDE:\n\t\t\tcase FILE_OPEN:\n\t\t\tcase FILE_CREATE:\n\t\t\tcase FILE_OVERWRITE:\n\t\t\t\tInformation = FILE_SUPERSEDED;\n\t\t\t\tbreak;",
"\t\t\tcase FILE_OPEN_IF:\n\t\t\t\tInformation = FILE_OPENED;\n\t\t\t\tbreak;",
"\t\t\tcase FILE_OVERWRITE_IF:\n\t\t\t\tInformation = FILE_OVERWRITTEN;\n\t\t\t\tbreak;",
"\t\t\tdefault:\n\t\t\t\tInformation = 0;\n\t\t\t\tbreak;\n\t\t}\n\t}",
"\tStream_Write_UINT32(irp->output, FileId);\n\tStream_Write_UINT8(irp->output, Information);\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_close(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tvoid* key;\n\tDRIVE_FILE* file;",
"\tif (!drive || !irp || !irp->Complete || !irp->output)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tfile = drive_get_file_by_id(drive, irp->FileId);\n\tkey = (void*)(size_t)irp->FileId;",
"\tif (!file)\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\telse\n\t{\n\t\tListDictionary_Remove(drive->files, key);",
"\t\tif (drive_file_free(file))\n\t\t\tirp->IoStatus = STATUS_SUCCESS;\n\t\telse\n\t\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\tStream_Zero(irp->output, 5); /* Padding(5) */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_read(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 Length;\n\tUINT64 Offset;",
"\tif (!drive || !irp || !irp->output || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 12)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, Length);\n\tStream_Read_UINT64(irp->input, Offset);\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tLength = 0;\n\t}\n\telse if (!drive_file_seek(file, Offset))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tLength = 0;\n\t}",
"\tif (!Stream_EnsureRemainingCapacity(irp->output, Length + 4))\n\t{\n\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\treturn ERROR_INTERNAL_ERROR;\n\t}\n\telse if (Length == 0)\n\t\tStream_Write_UINT32(irp->output, 0);\n\telse\n\t{\n\t\tBYTE* buffer = Stream_Pointer(irp->output) + sizeof(UINT32);",
"\t\tif (!drive_file_read(file, buffer, &Length))\n\t\t{\n\t\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\t\tStream_Write_UINT32(irp->output, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStream_Write_UINT32(irp->output, Length);\n\t\t\tStream_Seek(irp->output, Length);\n\t\t}\n\t}",
"\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_write(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 Length;\n\tUINT64 Offset;",
"\tvoid* ptr;",
"\n\tif (!drive || !irp || !irp->input || !irp->output || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, Length);\n\tStream_Read_UINT64(irp->input, Offset);\n\tStream_Seek(irp->input, 20); /* Padding */",
"\tptr = Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, Length))\n\t\treturn ERROR_INVALID_DATA;",
"\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tLength = 0;\n\t}\n\telse if (!drive_file_seek(file, Offset))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tLength = 0;\n\t}",
"\telse if (!drive_file_write(file, ptr, Length))",
"\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t\tLength = 0;\n\t}",
"\tStream_Write_UINT32(irp->output, Length);\n\tStream_Write_UINT8(irp->output, 0); /* Padding */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_query_information(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 FsInformationClass;",
"\tif (!drive || !irp || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t}\n\telse if (!drive_file_query_information(file, FsInformationClass, irp->output))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_set_information(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tDRIVE_FILE* file;\n\tUINT32 FsInformationClass;\n\tUINT32 Length;",
"\tif (!drive || !irp || !irp->Complete || !irp->input || !irp->output)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tStream_Read_UINT32(irp->input, Length);\n\tStream_Seek(irp->input, 24); /* Padding */\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (!file)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t}\n\telse if (!drive_file_set_information(file, FsInformationClass, Length, irp->input))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\tif (file && file->is_dir && !PathIsDirectoryEmptyW(file->fullpath))\n\t\tirp->IoStatus = STATUS_DIRECTORY_NOT_EMPTY;",
"\tStream_Write_UINT32(irp->output, Length);\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_query_volume_information(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT32 FsInformationClass;\n\twStream* output = NULL;\n\tchar* volumeLabel = { \"FREERDP\" };\n\tchar* diskType = { \"FAT32\" };\n\tWCHAR* outStr = NULL;\n\tint length;\n\tDWORD lpSectorsPerCluster;\n\tDWORD lpBytesPerSector;\n\tDWORD lpNumberOfFreeClusters;\n\tDWORD lpTotalNumberOfClusters;\n\tWIN32_FILE_ATTRIBUTE_DATA wfad;",
"\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\toutput = irp->output;",
"\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tGetDiskFreeSpaceW(drive->path, &lpSectorsPerCluster, &lpBytesPerSector, &lpNumberOfFreeClusters,\n\t &lpTotalNumberOfClusters);",
"\tswitch (FsInformationClass)\n\t{\n\t\tcase FileFsVolumeInformation:",
"\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232108.aspx */\n\t\t\tif ((length = ConvertToUnicode(sys_code_page, 0, volumeLabel, -1, &outStr, 0) * 2) <= 0)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"ConvertToUnicode failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, 17 + length); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 17 + length))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\tfree(outStr);\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tGetFileAttributesExW(drive->path, GetFileExInfoStandard, &wfad);\n\t\t\tStream_Write_UINT32(output, wfad.ftCreationTime.dwLowDateTime); /* VolumeCreationTime */\n\t\t\tStream_Write_UINT32(output,\n\t\t\t wfad.ftCreationTime.dwHighDateTime); /* VolumeCreationTime */\n\t\t\tStream_Write_UINT32(output, lpNumberOfFreeClusters & 0xffff); /* VolumeSerialNumber */\n\t\t\tStream_Write_UINT32(output, length); /* VolumeLabelLength */\n\t\t\tStream_Write_UINT8(output, 0); /* SupportsObjects */\n\t\t\t/* Reserved(1), MUST NOT be added! */\n\t\t\tStream_Write(output, outStr, length); /* VolumeLabel (Unicode) */\n\t\t\tfree(outStr);\n\t\t\tbreak;",
"\t\tcase FileFsSizeInformation:\n\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232107.aspx */\n\t\t\tStream_Write_UINT32(output, 24); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 24))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */\n\t\t\tStream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */\n\t\t\tStream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */\n\t\t\tStream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */\n\t\t\tbreak;",
"\t\tcase FileFsAttributeInformation:",
"\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232101.aspx */\n\t\t\tif ((length = ConvertToUnicode(sys_code_page, 0, diskType, -1, &outStr, 0) * 2) <= 0)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"ConvertToUnicode failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, 12 + length); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 12 + length))\n\t\t\t{\n\t\t\t\tfree(outStr);\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES |\n\t\t\t FILE_UNICODE_ON_DISK); /* FileSystemAttributes */\n\t\t\tStream_Write_UINT32(output, MAX_PATH); /* MaximumComponentNameLength */\n\t\t\tStream_Write_UINT32(output, length); /* FileSystemNameLength */\n\t\t\tStream_Write(output, outStr, length); /* FileSystemName (Unicode) */\n\t\t\tfree(outStr);\n\t\t\tbreak;",
"\t\tcase FileFsFullSizeInformation:\n\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232104.aspx */\n\t\t\tStream_Write_UINT32(output, 32); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 32))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT64(output, lpTotalNumberOfClusters); /* TotalAllocationUnits */\n\t\t\tStream_Write_UINT64(output,\n\t\t\t lpNumberOfFreeClusters); /* CallerAvailableAllocationUnits */\n\t\t\tStream_Write_UINT64(output, lpNumberOfFreeClusters); /* AvailableAllocationUnits */\n\t\t\tStream_Write_UINT32(output, lpSectorsPerCluster); /* SectorsPerAllocationUnit */\n\t\t\tStream_Write_UINT32(output, lpBytesPerSector); /* BytesPerSector */\n\t\t\tbreak;",
"\t\tcase FileFsDeviceInformation:\n\t\t\t/* http://msdn.microsoft.com/en-us/library/cc232109.aspx */\n\t\t\tStream_Write_UINT32(output, 8); /* Length */",
"\t\t\tif (!Stream_EnsureRemainingCapacity(output, 8))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t}",
"\t\t\tStream_Write_UINT32(output, FILE_DEVICE_DISK); /* DeviceType */\n\t\t\tStream_Write_UINT32(output, 0); /* Characteristics */\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\t\tStream_Write_UINT32(output, 0); /* Length */\n\t\t\tbreak;\n\t}",
"\treturn irp->Complete(irp);\n}",
"/* http://msdn.microsoft.com/en-us/library/cc241518.aspx */",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_silent_ignore(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT32 FsInformationClass;",
"\tif (!drive || !irp || !irp->output || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tStream_Write_UINT32(irp->output, 0); /* Length */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_query_directory(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tconst WCHAR* path;\n\tDRIVE_FILE* file;\n\tBYTE InitialQuery;\n\tUINT32 PathLength;\n\tUINT32 FsInformationClass;",
"\tif (!drive || !irp || !irp->Complete)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;",
"\tStream_Read_UINT32(irp->input, FsInformationClass);\n\tStream_Read_UINT8(irp->input, InitialQuery);\n\tStream_Read_UINT32(irp->input, PathLength);\n\tStream_Seek(irp->input, 23); /* Padding */\n\tpath = (WCHAR*)Stream_Pointer(irp->input);\n\tfile = drive_get_file_by_id(drive, irp->FileId);",
"\tif (file == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tStream_Write_UINT32(irp->output, 0); /* Length */\n\t}\n\telse if (!drive_file_query_directory(file, FsInformationClass, InitialQuery, path, PathLength,\n\t irp->output))\n\t{\n\t\tirp->IoStatus = drive_map_windows_err(GetLastError());\n\t}",
"\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_directory_control(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tswitch (irp->MinorFunction)\n\t{\n\t\tcase IRP_MN_QUERY_DIRECTORY:\n\t\t\treturn drive_process_irp_query_directory(drive, irp);",
"\t\tcase IRP_MN_NOTIFY_CHANGE_DIRECTORY: /* TODO */\n\t\t\treturn irp->Discard(irp);",
"\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\tStream_Write_UINT32(irp->output, 0); /* Length */\n\t\t\treturn irp->Complete(irp);\n\t}",
"\treturn CHANNEL_RC_OK;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp_device_control(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tStream_Write_UINT32(irp->output, 0); /* OutputBufferLength */\n\treturn irp->Complete(irp);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_process_irp(DRIVE_DEVICE* drive, IRP* irp)\n{\n\tUINT error;",
"\tif (!drive || !irp)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tirp->IoStatus = STATUS_SUCCESS;",
"\tswitch (irp->MajorFunction)\n\t{\n\t\tcase IRP_MJ_CREATE:\n\t\t\terror = drive_process_irp_create(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_CLOSE:\n\t\t\terror = drive_process_irp_close(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_READ:\n\t\t\terror = drive_process_irp_read(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_WRITE:\n\t\t\terror = drive_process_irp_write(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_QUERY_INFORMATION:\n\t\t\terror = drive_process_irp_query_information(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_SET_INFORMATION:\n\t\t\terror = drive_process_irp_set_information(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_QUERY_VOLUME_INFORMATION:\n\t\t\terror = drive_process_irp_query_volume_information(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_LOCK_CONTROL:\n\t\t\terror = drive_process_irp_silent_ignore(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_DIRECTORY_CONTROL:\n\t\t\terror = drive_process_irp_directory_control(drive, irp);\n\t\t\tbreak;",
"\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\terror = drive_process_irp_device_control(drive, irp);\n\t\t\tbreak;",
"\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\terror = irp->Complete(irp);\n\t\t\tbreak;\n\t}",
"\treturn error;\n}",
"static DWORD WINAPI drive_thread_func(LPVOID arg)\n{\n\tIRP* irp;\n\twMessage message;\n\tDRIVE_DEVICE* drive = (DRIVE_DEVICE*)arg;\n\tUINT error = CHANNEL_RC_OK;",
"\tif (!drive)\n\t{\n\t\terror = ERROR_INVALID_PARAMETER;\n\t\tgoto fail;\n\t}",
"\twhile (1)\n\t{\n\t\tif (!MessageQueue_Wait(drive->IrpQueue))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Wait failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}",
"\t\tif (!MessageQueue_Peek(drive->IrpQueue, &message, TRUE))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Peek failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}",
"\t\tif (message.id == WMQ_QUIT)\n\t\t\tbreak;",
"\t\tirp = (IRP*)message.wParam;",
"\t\tif (irp)\n\t\t{\n\t\t\tif ((error = drive_process_irp(drive, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"drive_process_irp failed with error %\" PRIu32 \"!\", error);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"fail:",
"\tif (error && drive && drive->rdpcontext)\n\t\tsetChannelError(drive->rdpcontext, error, \"drive_thread_func reported an error\");",
"\tExitThread(error);\n\treturn error;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_irp_request(DEVICE* device, IRP* irp)\n{\n\tDRIVE_DEVICE* drive = (DRIVE_DEVICE*)device;",
"\tif (!drive)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (!MessageQueue_Post(drive->IrpQueue, NULL, 0, (void*)irp, NULL))\n\t{\n\t\tWLog_ERR(TAG, \"MessageQueue_Post failed!\");\n\t\treturn ERROR_INTERNAL_ERROR;\n\t}",
"\treturn CHANNEL_RC_OK;\n}",
"static UINT drive_free_int(DRIVE_DEVICE* drive)\n{\n\tUINT error = CHANNEL_RC_OK;",
"\tif (!drive)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tCloseHandle(drive->thread);\n\tListDictionary_Free(drive->files);\n\tMessageQueue_Free(drive->IrpQueue);\n\tStream_Free(drive->device.data, TRUE);\n\tfree(drive->path);\n\tfree(drive);\n\treturn error;\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_free(DEVICE* device)\n{\n\tDRIVE_DEVICE* drive = (DRIVE_DEVICE*)device;\n\tUINT error = CHANNEL_RC_OK;",
"\tif (!drive)\n\t\treturn ERROR_INVALID_PARAMETER;",
"\tif (MessageQueue_PostQuit(drive->IrpQueue, 0) &&\n\t (WaitForSingleObject(drive->thread, INFINITE) == WAIT_FAILED))\n\t{\n\t\terror = GetLastError();\n\t\tWLog_ERR(TAG, \"WaitForSingleObject failed with error %\" PRIu32 \"\", error);\n\t\treturn error;\n\t}",
"\treturn drive_free_int(drive);\n}",
"/**\n * Helper function used for freeing list dictionary value object\n */\nstatic void drive_file_objfree(void* obj)\n{\n\tdrive_file_free((DRIVE_FILE*)obj);\n}",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT drive_register_drive_path(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, const char* name,\n const char* path, BOOL automount)\n{\n\tsize_t i, length;\n\tDRIVE_DEVICE* drive;\n\tUINT error = ERROR_INTERNAL_ERROR;",
"\tif (!pEntryPoints || !name || !path)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Invalid parameters: pEntryPoints=%p, name=%p, path=%p\", pEntryPoints,\n\t\t name, path);\n\t\treturn ERROR_INVALID_PARAMETER;\n\t}",
"\tif (name[0] && path[0])\n\t{\n\t\tsize_t pathLength = strnlen(path, MAX_PATH);\n\t\tdrive = (DRIVE_DEVICE*)calloc(1, sizeof(DRIVE_DEVICE));",
"\t\tif (!drive)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}",
"\t\tdrive->device.type = RDPDR_DTYP_FILESYSTEM;\n\t\tdrive->device.IRPRequest = drive_irp_request;\n\t\tdrive->device.Free = drive_free;\n\t\tdrive->rdpcontext = pEntryPoints->rdpcontext;\n\t\tdrive->automount = automount;\n\t\tlength = strlen(name);\n\t\tdrive->device.data = Stream_New(NULL, length + 1);",
"\t\tif (!drive->device.data)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tfor (i = 0; i < length; i++)\n\t\t{\n\t\t\t/* Filter 2.2.1.3 Device Announce Header (DEVICE_ANNOUNCE) forbidden symbols */\n\t\t\tswitch (name[i])\n\t\t\t{\n\t\t\t\tcase ':':\n\t\t\t\tcase '<':\n\t\t\t\tcase '>':\n\t\t\t\tcase '\\\"':\n\t\t\t\tcase '/':\n\t\t\t\tcase '\\\\':\n\t\t\t\tcase '|':\n\t\t\t\tcase ' ':\n\t\t\t\t\tStream_Write_UINT8(drive->device.data, '_');\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tStream_Write_UINT8(drive->device.data, (BYTE)name[i]);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tStream_Write_UINT8(drive->device.data, '\\0');",
"\t\tdrive->device.name = (const char*)Stream_Buffer(drive->device.data);\n\t\tif (!drive->device.name)\n\t\t\tgoto out_error;",
"\t\tif ((pathLength > 1) && (path[pathLength - 1] == '/'))\n\t\t\tpathLength--;",
"\t\tif (ConvertToUnicode(sys_code_page, 0, path, pathLength, &drive->path, 0) <= 0)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ConvertToUnicode failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tdrive->files = ListDictionary_New(TRUE);",
"\t\tif (!drive->files)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tListDictionary_ValueObject(drive->files)->fnObjectFree = drive_file_objfree;\n\t\tdrive->IrpQueue = MessageQueue_New(NULL);",
"\t\tif (!drive->IrpQueue)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto out_error;\n\t\t}",
"\t\tif ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)drive)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"RegisterDevice failed with error %\" PRIu32 \"!\", error);\n\t\t\tgoto out_error;\n\t\t}",
"\t\tif (!(drive->thread =\n\t\t CreateThread(NULL, 0, drive_thread_func, drive, CREATE_SUSPENDED, NULL)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"CreateThread failed!\");\n\t\t\tgoto out_error;\n\t\t}",
"\t\tResumeThread(drive->thread);\n\t}",
"\treturn CHANNEL_RC_OK;\nout_error:\n\tdrive_free_int(drive);\n\treturn error;\n}",
"#ifdef BUILTIN_CHANNELS\n#define DeviceServiceEntry drive_DeviceServiceEntry\n#else\n#define DeviceServiceEntry FREERDP_API DeviceServiceEntry\n#endif",
"/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)\n{\n\tRDPDR_DRIVE* drive;\n\tUINT error;\n#ifdef WIN32\n\tchar* dev;\n\tint len;\n\tchar devlist[512], buf[512];\n\tchar* bufdup;\n\tchar* devdup;\n#endif\n\tdrive = (RDPDR_DRIVE*)pEntryPoints->device;\n#ifndef WIN32\n\tsys_code_page = CP_UTF8;",
"\tif (strcmp(drive->Path, \"*\") == 0)\n\t{\n\t\t/* all drives */\n\t\tfree(drive->Path);\n\t\tdrive->Path = _strdup(\"/\");",
"\t\tif (!drive->Path)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\t}\n\telse if (strcmp(drive->Path, \"%\") == 0)\n\t{\n\t\tfree(drive->Path);\n\t\tdrive->Path = GetKnownPath(KNOWN_PATH_HOME);",
"\t\tif (!drive->Path)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\t}",
"\terror = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);\n#else\n\tsys_code_page = GetACP();",
"\t/* Special case: path[0] == '*' -> export all drives */\n\t/* Special case: path[0] == '%' -> user home dir */\n\tif (strcmp(drive->Path, \"%\") == 0)\n\t{\n\t\tGetEnvironmentVariableA(\"USERPROFILE\", buf, sizeof(buf));\n\t\tPathCchAddBackslashA(buf, sizeof(buf));\n\t\tfree(drive->Path);\n\t\tdrive->Path = _strdup(buf);",
"\t\tif (!drive->Path)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}",
"\t\terror = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);\n\t}\n\telse if (strcmp(drive->Path, \"*\") == 0)\n\t{\n\t\tint i;\n\t\t/* Enumerate all devices: */\n\t\tGetLogicalDriveStringsA(sizeof(devlist) - 1, devlist);",
"\t\tfor (dev = devlist, i = 0; *dev; dev += 4, i++)\n\t\t{\n\t\t\tif (*dev > 'B')\n\t\t\t{\n\t\t\t\t/* Suppress disk drives A and B to avoid pesty messages */\n\t\t\t\tlen = sprintf_s(buf, sizeof(buf) - 4, \"%s\", drive->Name);\n\t\t\t\tbuf[len] = '_';\n\t\t\t\tbuf[len + 1] = dev[0];\n\t\t\t\tbuf[len + 2] = 0;\n\t\t\t\tbuf[len + 3] = 0;",
"\t\t\t\tif (!(bufdup = _strdup(buf)))\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t\t}",
"\t\t\t\tif (!(devdup = _strdup(dev)))\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"_strdup failed!\");\n\t\t\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t\t\t}",
"\t\t\t\tif ((error = drive_register_drive_path(pEntryPoints, bufdup, devdup, TRUE)))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\terror = drive_register_drive_path(pEntryPoints, drive->Name, drive->Path, drive->automount);\n\t}",
"#endif\n\treturn error;\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
] |
PreciseBugs
|
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
| 320
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.